c# - 定义仅在一个类中定义 ICollection<> 的多对多连接

标签 c# entity-framework .net-standard

我有一个 .NET 应用程序,其验证逻辑外包给了 .NET Core API。他们都使用一些模型和逻辑,我希望他们使用(.net 标准)Nuget 包中的相同类。我使用Entity Framework code-first 的主要问题是,一些常见模型也在数据库中,但我不想包括 f.e. ApplicationUser 在 nuget 包中。 有一个与 ApplicationUser 有多对多连接的模型,我不想在其中定义 ICollection

所以我的“本地”类看起来像这样:

public class ApplicationUser : IdentityUser
{
    ....

    public ICollection<Institute> Institutes { get; set; }

    ....
}

我的“远程”类(class)如下所示:

public class Institute
{
    ....

    public ICollection<ApplicationUser> Users { get; set; }

    ....
}

但我不希望研究所拥有这个 public ICollection<ApplicationUser> Users { get; set; }但我希望 EF 映射多对多连接。如果我从 Institute 类中删除它,下一次迁移将删除整个 ApplicationUserInstitute 连接表。

我想到了某种继承解决方案,但我认为 future 的开发会很痛苦。欢迎所有可能的解决方案。

最佳答案

您需要显式覆盖 OnModelCreating()在您的上下文中并在那里指定多对多关系:

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<ApplicationUser>()
            .HasMany(s => s.Institues)
            .WithMany()
            .Map(cs =>
            {
                cs.MapLeftKey("UserRefId");
                cs.MapRightKey("InstituteRefId");
                cs.ToTable("UserInsitute");
            });
        }

我使用了 this article 中的实体生成模式。唯一的区别是我删除了 public virtual ICollection<Student> Students { get; set; }来自 Course .

enter image description here

关于c# - 定义仅在一个类中定义 ICollection<> 的多对多连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57391863/

相关文章:

javascript - HyperLink 上带参数的 Js 函数调用

c# - 如何在 Windows UWP 中的同一个 WebView(不是新窗口)中打开弹出窗口?

c# - XAML intellisense 不适用于 <StaticResource/>

entity-framework - Entity Framework 数据库开发入门(代码优先)

odbc - AWS RedShift - .NET Core(ODBC 支持?)

c# - 使用事务内存数据库进行单元测试时,如何抑制 InMemoryEventId.TransactionIgnoredWarning?

c# - Entity Framework 在第一次查询时大约需要 30 秒

.net - netstandard2.0 (.net standard 2.0) 类库无法引用 net461 (.net Framework 4.6.1) 类库

c# - TryReset CancellationSource .NET 标准

c# - 如果我忽略用于某个过程的 dbset,我将无法使用 EF Core 获取该过程