【问题标题】:2 Foreign Keys in Entity Framework Code First Approach2 实体框架代码优先方法中的外键
【发布时间】:2014-07-21 06:50:59
【问题描述】:

我正在 MVC 5、Visual Studio 2013、EF 6(代码优先方法)中创建应用程序。我已经实施了身份并且工作正常。现在我想创建一个需要 2 个外键关系的表 - 一个来自 dbo.AspNetUsers,另一个来自第二个表(我们将其命名为 Table2)。

在我的 IdentityModel.cs 中,我有以下代码:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Table2> Table2 { get; set; }

    public ApplicationDbContext() : base("ConnectionString", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

这是我的桌子2:

[Key]
[Display(Name = "ID")]
public int ID { get; set; }

[Required]
[StringLength(200, MinimumLength = 10)]
[Display(Name = "Col1")]
public string Col1{ get; set; }

[Required]
[StringLength(4000, MinimumLength = 10)]
[Display(Name = "Col2")]
public string Col2 { get; set; }

现在,我需要创建一个表 (NewTable),其中有 2 个外键 - UserID(来自 dbo.AspNetUsers)和另一个来自 Table2。

谁能告诉我该怎么做?我已经用谷歌搜索了它,但未能找到任何令人满意的答案。

【问题讨论】:

    标签: asp.net asp.net-mvc entity-framework asp.net-identity


    【解决方案1】:

    很简单,只需创建一个 Navigation 属性即可。

    例子:

    public virtual ApplicationUser User { get; set; }
    

    编辑:

    我建议合并两个数据库上下文。从长远来看,它将避免许多问题。示例:

    public class MyDbContext : IdentityDbContext<ApplicationUser>
        {
            public MyDbContext () : base("DbConn",false) {
    
            }
    
            public MyDbContext (string connectionString):base(connectionString,false)
            {
    
            }
            public DbSet<Table1> MyTable1{ get; set; }
            public DbSet<Table2> MyTable2{ get; set; }
       }
    

    【讨论】:

    • 我已经应用了它,但它只会为 dbo.AspNetUsers 创建一个外键(我认为)。如果我对 Table2 应用相同的代码,我将需要创建另一个 DbContext 类(因为我正在使用 ApplicationDbContext 类)。但是在创建视图时,我需要指定一个上下文类,并且当时我将指定哪个上下文类。
    • 我建议将两个数据库上下文合并为一个。请检查编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2015-02-24
    • 2021-01-05
    相关资源
    最近更新 更多