Entity Framework 代码优先流利 api 关系
Entity Framework Code first fluent api relationships
我有一个 table Items
和 table Services
。
每个项目都需要与一项服务相关。
如何在 EF Fluent api 中通过 ItemServices
关系 table 编写这两个之间的关系?
这里是类
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 对象中有关系 table,所以我不想像 item.ItemService.Service
那样使用它,而是作为 item.Service
您正在使用 Entity Framework 的哪个版本?
如果您询问有关 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; }
我有一个 table Items
和 table Services
。
每个项目都需要与一项服务相关。
如何在 EF Fluent api 中通过 ItemServices
关系 table 编写这两个之间的关系?
这里是类
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 对象中有关系 table,所以我不想像 item.ItemService.Service
那样使用它,而是作为 item.Service
您正在使用 Entity Framework 的哪个版本?
如果您询问有关 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; }