2016-06-12 127 views
1

我有一個表Items和表Services實體框架代碼第一流利的API關係

每個項目都需要與一個服務有關。

如何在EF Fluent api中通過ItemServices關係表編寫2個關係?

這裏是班

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.ItemService.Service,但作爲一個item.Service

回答

1

在您正在使用哪個版本的實體框架?

如果你問EF核心,那麼你可以在這裏找到很好的幫助:


BTW:我也有類似的情況在我的項目,它的工作由慣例。

當然,我在配置DbSet<>ApplicationDbContext

(我不知道它是如何在早期版本的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; } 
相關問題