【问题标题】:Entity Framework Code first fluent api relationshipsEntity Framework Code 先流畅的 api 关系
【发布时间】:2016-06-14 06:43:07
【问题描述】:

我有一张桌子Items 和一张桌子Services

每个项目都需要与一项服务相关。

如何在 EF Fluent api 中通过ItemServices 关系表编写这两者之间的关系?

这里是类

public class Item
{
   public Guid Id { get; private set; }
   public Service Service { get;  private set; }
}

public class ItemService
{
    public int ServiceId { get; set; }

    [ForeignKey(nameof(ServiceId))]
    public Service Service { get; set; }

    public int ItemId { get; set; }

    [ForeignKey(nameof(ItemId))]
    public Item Item { get; set; }
}

public class Service
{       
    public int Id { get; private set; }

    public string ServiceCode { get; set; }
}

请注意,我不想在我的 Item 对象中有关系表,所以我不想像 item.ItemService.Service 那样使用它,而是作为 item.Service 使用它

【问题讨论】:

    标签: c# entity-framework ef-fluent-api


    【解决方案1】:

    您正在使用哪个版本的实体框架?

    如果您询问 EF Core,那么您可以在这里找到非常好的帮助:


    顺便说一句:我的项目中有类似的情况,它按惯例工作。

    当然我已经在我的ApplicationDbContext中配置了DbSet<>

    (我不确定它在早期版本的 EF 中是如何工作的):


    是否还有其他原因使用 ItemService 对象或仅用于关系目的?

    如果您仅将ItemService 用于关系目的,那么您的情况就不需要它 - 尝试类似的方法:

    public class Item
    {
       public Guid Id { get; set; }
       public Service Service { get; set; }
    }
    
    public class Service
    {       
        public int Id { get; set; }    
        public string ServiceCode { get; set; }
    
        public Item Item { get; set; } //for One to One relationship
        // or
        public virtual ICollection<Item> Items { get; set; } // for One service to Many Items relationship
    }
    

    ApplicaitionDbContext:

    public virtual DbSet<Item> Items { get; set; }
    public virtual DbSet<Service> Services { get; set; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多