Do DataAnnotations do the same thing as Fluent API methods?
For example, does .HasRequired == [Required]?
.HasKey == [Key]?
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?
Can I use a combonation of DataAnnotations and Fluent API; or, is it one or the other?
Must I map M:M relationships for both classes involved i.e.
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");
});
}
Thanks.
Yes, you can use a combination. However it’s generally better to pick one or the other. I prefer fluent, as it keeps certain persistence concerns out of the entity classes.
Yes. Also, .IsRequired == [Required]
No, you only need to map one side of the relationship. You can map both sides, but if you change the relationship, you will then need to modify both sets of code. Also, when you map both sides, both mappings must resolve to the same result (i.e. same foreign key declaration in the db).
Yes, unless your property name is Id or PersonId / ProductId / OrderId / WhateverEntityNameId. By convention, EF will guess that these are your key properties. However it never hurts to make this explicit by invoking .HasKey on your modelBuilder.