DataAnnotations 与 Fluent API 方法做同样的事情吗?
例如,.HasRequired == [Required] 吗?
.HasKey == [键]?
如果我不希望表 pk 字段生成为 ClassNameClassNameID(如果我对 pk 属性使用 ClassNameID 格式),我是否必须使用 [Key] 标记类键或使用 .HasKey?
我可以使用 DataAnnotations 和 Fluent API 的组合吗?或者,是其中之一吗?
我是否必须映射所涉及的两个类的 M:M 关系,即
public class Foo
{
public ICollection<Bar> Bars
}
public class Bar
{
public ICollection<Bar> Foos
}
public class Context : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Foo>()
.HasMany(f => f.Bars).WithMany(b => b.Foos)
.Map(t =>
{
t.MapLeftKey("FooID");
t.MapRightKey("BarId");
t.ToTable("FooBar");
});
modelBuilder.Entity<Bar>()
.HasMany(b => b.Foos).WithMany(f => f.Bars)
.Map(t =>
{
t.MapLeftKey("FooID");
t.MapRightKey("BarId");
t.ToTable("FooBar");
});
}
谢谢。
最佳答案
Can I use a combonation of DataAnnotations and Fluent API; or, is it one or the other?
是的,您可以使用组合。然而,通常选择其中之一更好。我更喜欢 Fluent,因为它可以将某些持久性问题排除在实体类之外。
Do DataAnnotations do the same thing as Fluent API methods?
For example, does .HasRequired == [Required]?
.HasKey == [Key]?
是的。另外,.IsRequired == [必需]
Must I map M:M relationships for both classes involved
不,您只需要映射关系的一侧。您可以映射两侧,但如果更改关系,则需要修改两组代码。此外,当您映射两侧时,两个映射必须解析为相同的结果(即数据库中相同的外键声明)。
Must I mark class key with [Key] or use .HasKey if I do not want my table pk field generated as ClassNameClassNameID if I am using ClassNameID format for my pk property?
是的,除非您的属性名称是 Id 或 PersonId/ProductId/OrderId/WhatEntityNameId。按照惯例,EF 会猜测这些是您的关键属性。然而,通过在模型构建器上调用 .HasKey 来明确这一点永远不会有坏处。
关于asp.net-mvc - 流畅的 API 和数据注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11476984/