【问题标题】:Entity Framework join table with additional field带有附加字段的实体框架连接表
【发布时间】:2013-07-09 13:11:05
【问题描述】:

关于实体框架的最佳实践问题。

我有一个 Cases 表和一个 Users 表,我想将它们加入到多对多关系中。但是,我希望连接本身通过“UserType”字段存储有关该关系的信息。

在 SQL 中很容易做到 - 两个主要数据表和第三个用外键链接这两个数据表并包含一个额外的 UserType 列。

   create table #user ( UserId int, Info nvarchar(4000) )
   create table #case ( CaseId int, Info nvarchar(4000) )
   create table #jointable ( UserId int, CaseId int, UserType nvarchar(99))

让我感到困惑的是 EF 自己定义连接表的能力,将其从开发人员手中夺走。在这种情况下,我是否需要将这三个类都定义为 EF 类,或者有没有一种方法可以构建它,我只定义两个类,Case 和 User,让 EF 为我处理连接,同时仍然获得我的 UserType?

我使用的是“代码优先”EF,但这对解决方案应该有很大的影响。

干杯, 马特

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    EF 只负责创建具有简单多对多关系的连接表。与您的情况一样,除了明确创建联接类之外,我没有看到任何其他方式

    public class UserCase
    {
         public virtual User User { get; set; }
         public virtual Case Case { get; set; }
    
         public virtual string UserType { get; set; }
    }
    

    【讨论】:

      【解决方案2】:

      使用 EF 实现此目的的唯一方法是创建两个 one-to-many 关系:

      public class User
      {
          public int UserId {get; set;}
          public string Info {get; set;}
      
          public virtual ICollection<UserCase> UserCase {get; set;}
      }
      public class Case
      {
          public int CaseId {get; set;}
          public string Info {get; set;}
      
          public virtual ICollection<UserCase> UserCase {get; set;}
      }
      public class UserCase
      {
          public int CaseId {get; set;}
          public int UserId {get; set;}
      
          public virtual Case Case {get; set;}
          public virtual User User {get; set;}
      
          public string UserType {get; set;}
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多