2016-11-20 12 views
1

我有一個名爲TypeListItem的模型,其中有三個屬性(Id, TypeListId, Name),其中包含一堆列表。實體框架:來自同一模型的多個導航屬性導致添加遷移時出錯

例如:

ProductType: Strong, Weak, Medium

ProductCategory: Category 1, Category 2, Category 3

我有一個產品型號,看起來像這樣:

public int Id {get; set;} 
public string Name {get; set;} 
public int ProductTypeId {get; set;} 
public int ProductCategoryId {get; set;} 

// Navigation Properties 
public TypeListItem ProductType {get; set;} 
public TypeListItem ProductCategory {get; set;} 

然而,當我去添加一個遷移,然後dotnet ef database update「我得到一個錯誤:

Introducing FOREIGN KEY constraint : FK_Product_TypeListItem_ProductCategoryId on table 'Product' may cause cycles or multiple cascade paths.

我也有t他以下使用流利的API:

builder.Entity<Product>() 
    .Property(p => p.ProductTypeId) 
    .IsRequired(); 
builder.Entity<Product>() 
    .Property(p => p.ProductCategoryId) 
    .IsRequired(); 

我相信錯誤是因爲我有兩個導航屬性使用相同的對象,都是必需的。

有什麼建議嗎?我的模型有問題嗎?

這樣做對ef core有意義嗎?

builder.Entity<Product>() 
     .HasOne(p => p.ProductType) 
     .WithOne().OnDelete(DeleteBehavior.Restrict); 

    builder.Entity<Product>() 
     .HasOne(p => p.ProductCategory) 
     .WithOne().OnDelete(DeleteBehavior.Restrict); 
+0

可以顯示'TypeListItem'的代碼? – Sampath

+0

沒有什麼。 Just Id,TypeListId和Name屬性。 –

回答

1

您需要使用OnDelete(DeleteBehavior.Restrict)如下所示。

注:

Restrict : The delete operation is not applied to dependent entities. The dependent entities remain unchanged.

builder.Entity<Product>() 
    .Property(p => p.ProductTypeId) 
    .WithOne() 
    .OnDelete(DeleteBehavior.Restrict); 

builder.Entity<Product>() 
    .Property(p => p.ProductCategoryId) 
    .WithOne() 
    .OnDelete(DeleteBehavior.Restrict); 

你可以看到更多在這裏:Cascade Delete

+0

我相信這是EF6的答案,但我需要能夠用EF Core做到這一點,我認爲他們改變了語法。請參閱我更新的帖子。你認爲空的WithOne()有意義嗎? https://docs.microsoft.com/en-us/ef/core/modeling/relationships?highlight=cascade#cascade-delete –

+0

是的,你是對的,我已經更新了答案。 – Sampath

+0

我不認爲你的答案中的語法是有效的。我相信你不能在同一聲明中加入IsRequired和WithOne。否則答案是正確的。 –