一、EF Core 默認約定的導航屬性
1、如果兩個類型之間找到一對導航屬性,則它們將被配置為同一關系的反轉導航屬性。
public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List<Post> Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } }
2.依賴實體(多端的實體)包含名稱與其中一種模式相匹配的屬性,則該屬性將被配置為外鍵:
a.依賴主體設置:導航屬性、外鍵屬性(導航屬性名+主體主鍵名)
public class Blog { public int BlogId { get; set; } public string Url { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogModelBlogId { get; set; } public Blog BlogModel { get; set; } }
a.依賴主體設置:導航屬性、外鍵屬性(導航屬性名+Id)
public class Blog { public int BlogId { get; set; } public string Url { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogModelBlogId { get; set; } public Blog BlogModel { get; set; } }
c.依賴主體設置:導航屬性、外鍵屬性(主體類型名+主體主鍵名)
public class Blog { public int BlogId { get; set; } public string Url { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogBlogId { get; set; } public Blog BlogModel { get; set; } }
d.依賴主體設置:導航屬性、外鍵屬性(主體類型名+Id)
public class Blog { [Key] public int BId { get; set; } public string Url { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog BlogModel { get; set; } }
3.無外鍵屬性:如果未找到外鍵屬性,則會引入名稱為 <navigation property name><principal key property name>
或 <principal entity name><principal key property name>
在此示例中,隱藏外鍵是 BlogId
public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List<Post> Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public Blog Blog { get; set; } }
4.只包含一個導航屬性(無反向導航,沒有外鍵屬性)就足以具有約定定義的關系。 還可以有一個導航屬性和一個外鍵屬性
public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List<Post> Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } }
5.手動設置
a.數據注解方式
public int BlogForeignKey { get; set; } [ForeignKey("BlogForeignKey")] //設置外鍵 public Blog Blog { get; set; }
b.Fluent API 方式
odelBuilder.Entity<Post>().HasOne(p => p.Blog).WithMany(b =>
b.Posts).HasForeignKey(p => p.BlogForeignKey);