Unable to determine the main end of the association.

In such an association, I get the error message "It is not possible to determine the main end of the association between the" Foo "and" Bar "types. The main end of this association must be explicitly configured using either a free communication API or data annotation."

public class Foo { public int Id { get; set; } public int? MainBarId { get; set; } public virtual Bar MainBar { get; set; } [InverseProperty("Foo")] public virtual ICollection<Bar> Bars { get; set; } } public class Bar { public int Id { get; set; } public int FooId { get; set; } public virtual Foo Foo { get; set; } public int? OldFooId { get; set; } public virtual Foo OldFoo { get; set; } } 

Here, Foo has a collection of bars and can have a main bar (MainBar). The bar was always associated with Foo, but could have a link to another Foo (OldFoo).

  • How to match this in EF with data annotations?
  • If this is not possible in Data Annotations, how to do it fluently?
+4
source share
1 answer

In terms of [InverseProperty("Foo")] you indicate to EF that Bar.Foo and Foo.Bars are paired properties from one to many associations, so clear.

Then there is Foo.MainBar and Bar.OldFoo . EF does not know how they are connected. They can be combined into a one-to-one association, they can be independent, i.e. With "multiple" plurality on the other hand. Therefore you must say EF.

I assume that the properties are independent, i.e. that a Bar can have OldFoo without requiring that this Bar be a Foo MainBar at the same time. Then it is enough to provide EF with information about one of the properties:

 modelBuilder.Entity<Bar>().HasOptional(f => f.OldFoo).WithMany() .HasForeignKey(f => f.OldFooId); 

or

 modelBuilder.Entity<Foo>().HasOptional(f => f.MainBar) .WithRequired(b => b.OldFoo) 

Since there are no inverse properties paired with these "one" ends of associations, you cannot do this with data annotations (there are no properties to decorate with attributes).

+7
source

Source: https://habr.com/ru/post/1480489/


All Articles