[英]Entity Framework Code First: How can I create a One-to-Many AND a One-to-One relationship between two tables?
[英]How to create nullable one-to-many relationship in Entity Framwork 6 code first
我首先使用 EF 6.1 代碼構建應用程序。 實體模型包含以下類:
public enum UnitSystem {
English,
Metric
}
public enum UnitTypes {
Volume,
Weight,
Other
}
public class Unit {
[DatabaseGenerated( DatabaseGeneratedOption.Identity ), Key]
public int UnitId { get; set; }
[Required, MaxLength( 128 ), Index( IsUnique = true )]
public string UnitName { get; set; }
[Required]
public UnitSystem UnitSystem { get; set; }
[Required]
public UnitTypes UnitType { get; set; }
public virtual ICollection<Item> Items { get; set; }
}
public class Item {
[DatabaseGenerated( DatabaseGeneratedOption.Identity ), Key]
public int ItemId { get; set; }
[Required, MaxLength( 128 ), Index( IsUnique = true )]
public string ItemName { get; set;
[Required]
public int UnitId { get; set; }
[ForeignKey( "UnitId" )]
public virtual Unit Units { get; set; }
/// Other unimportant properties
}
public class UnitConversion {
[Required, Key, Column( Order = 0 )]
public int FromUnitId { get; set; }
[ForeignKey( "FromUnitId" )]
public virtual Unit FromUnit { get; set; }
[Required, Key, Column( Order = 1)]
public int ToUnitId { get; set; }
[ForeignKey( "ToUnitId" )]
public virtual Unit ToUnit { get; set; }
[Key, Column( Order = 2 )]
public int? ItemId { get; set; }
public virtual Item Item { get; set; }
[Required]
public double ConversionFactor { get; set; }
}
當 EF 構建數據庫時,我收到“Introducing FOREIGN KEY CONSTRAINT”消息。 我需要ItemId
屬性可以為空,如果它不為空,我需要它是Items
表的外鍵。
創建這種關系以避免級聯刪除錯誤的正確方法是什么?
編輯
我不再在ItemId
列上收到錯誤消息; 現在我為FromUnitId
或ToUnitId
列或兩者都得到它。
我已經向Unit
類添加了導航屬性:
[ForeignKey("FromUnitId")]
public virtual ICollection<UnitConversion> FromConversions { get; set; }
[ForeignKey("ToUnitId")]
public virtual ICollection<UnitConversion> ToConversions { get; set; }
這是我收到的錯誤消息的全文:
在表“UnitConversions”上引入 FOREIGN KEY 約束“FK_dbo.UnitConversions_dbo.Units_ToUnitId”可能會導致循環或多個級聯路徑。 指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 約束。
UnitConversions
表和Units
表之間應該存在零或一對多的關系。 當我嘗試創建對modelBuiloder.Entity<UnitConversions>().WillCascadeOnDelete(false)
的調用時,IntelliSense 不顯示WillCascadeOnDelete
方法,並且代碼不會編譯。
首先,我建議您快速閱讀entityframeworktutorial以確保您按照建議設置了密鑰。 對於 1 對 1 的關系,這有點棘手; 基本上'Child'的主鍵是'Parent'的外鍵。
或者,您可以在數據上下文中使用 fluent API 並執行以下操作以確保關系和級聯按預期進行:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Student>().HasOptional(e => e.StudentAddress)
.WithRequired(m => m.Student);
modelBuilder.Entity<StudentAddress>.WillCascadeOnDelete(false);
}
這表示學生有一個可選的學生地址,學生地址有一個必需的學生,當學生地址被刪除時,學生不是。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.