在我們MVC4應用程序,我們有一個WeekDay
型號:一比一的關係指出,多重無效
public class WeekDay
{
[Key]
public int WeekDayId { get; set; }
[Required]
[Display(Name = "Dag")]
public string Day { get; set; }
[ForeignKey("Shop")]
public int ShopId { get; set; }
public virtual Shop Shop { get; set; }
}
而且Shop
型號:
public class Shop
{
public int ShopId { get; set; }
[Display(Name = "Winkel")]
public string Name { get; set; }
public int WeekDayId { get; set; }
public virtual WeekDay WeekDay { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
我們需要一個一對一關係從WeekDay
到Shop
和其他方式(以便每個商店有一個工作日,反之亦然)。不幸的是上面的代碼提供了以下錯誤:
Multiplicity is not valid in Role 'Shop_WeekDay_Target' in relationship 'Shop_WeekDay'. Because
the Dependent Role properties are not the key properties, the upper bound of the multiplicity of
the Dependent Role must be '*'.
我們試圖在互聯網上找到各種事情來解決這個問題,但似乎沒有工作(它沒有當我們增加了兩個主鍵建立,但隨後失敗同時運行種子方法,我們得到這個錯誤:The index 'IX_ShopId' is dependent on column 'ShopId'. ALTER TABLE ALTER COLUMN ShopId failed because one or more objects access this column.
)。
有沒有人知道如何在這種情況下一對一的關係?
/編輯添加:
modelBuilder.Entity<WeekDay>()
.HasRequired(a => a.Shop)
.WithMany()
.HasForeignKey(u => u.ShopId);
modelBuilder.Entity<Shop>()
.HasRequired(a => a.WeekDay)
.WithMany()
.HasForeignKey(u => u.WeekDayId);
到DbContext
使一個成功的遷移,但update-database
給出了錯誤:
Introducing FOREIGN KEY constraint 'FK_dbo.WeekDays_dbo.Shops_ShopId' on table 'WeekDays' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors.
和設置WillCascadeOnDelete
爲false,給出了錯誤:
The index 'IX_ShopId' is dependent on column 'ShopId'. ALTER TABLE ALTER COLUMN ShopId failed because one or more objects access this column.
/編輯3
我的數據庫結構如下所示:
現在,我通過不使一個一對一的關係只有一種方式「解決」問題,這樣對Shop
與WeekDay
匹配我需要首先查詢WeekDay
表,然後查看哪些商店匹配。然後,我可以使用ShopId
進行進一步查詢,以僅從當前商店中選擇Categories
。如果你可以從Shop
到WeekDay
,那麼它會更清潔,這樣我只需要查詢一次。
我不在乎它是否是一對多,如果它很難做(我只會用很多),但它應該是相反的方式(從商店到平日而不是平日到商店) 。從右上角可以看出,一對多是錯誤的。
你可以發佈你的表定義嗎? –
@BrianDriscoll你是什麼意思的表定義?是不是因爲te模型定義了表格? –
@BrianDriscoll - 這是代碼優先的數據庫設計。這些表格是從代碼生成的。 –