【问题标题】:How to specify a list of foreign keys in Entity Framework?如何在实体框架中指定外键列表?
【发布时间】:2017-02-13 15:43:14
【问题描述】:

如何使用数据注释或 fluentapi 指定模型中的字符串列表,例如外键列表?我知道我可以在列表中指定 User 模型,但我想要一个字符串列表。

模型示例:

public class Allocation
{
      [Key]
      public int Id { get; set; }
      ...
      public List<string> Users { get; set; }
}

public class User
{
     [Key]
     public string Id { get; set; }
     ...
}

【问题讨论】:

    标签: c# asp.net sql-server entity-framework ef-fluent-api


    【解决方案1】:

    即使是专家开发人员在实体框架方面也失败了,所以我要告诉你一个小秘密。 编写您希望拥有的代码

    就您的场景而言,您将事情不必要地复杂化了。让 Entity Framework 完成它的工作并为您处理关系!

    你需要为这种关系建模只是......

    public class Allocation
    {
        public int Id { get; set; }
        public virtual ICollection<User> Users { get; set; }
    }
    
    public class User
    {
        public int Id { get; set; }
        public virtual Allocation Allocation { get; set; }
    }
    

    现在请注意,我没有编写我希望拥有的代码,但那是因为我希望我拥有的代码对于这个问题来说太过分了,而且非常高级。但是,如果您确实想深入研究这个主题并了解 Entity Framework 真正能为您做什么,我会从这里开始......

    https://lostechies.com/jimmybogard/2010/02/04/strengthening-your-domain-a-primer/

    【讨论】:

      猜你喜欢
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多