简体   繁体   中英

Configuring one to Many relationship in asp.net with Entity Framework 6 with Fluent API

I'm getting error before migration that says

The navigation property quotes in Book is configured with conflicting municipalities

Please help!

public partial class Book 
{ 
    public virtual ICollection<Quote> Quotes { get; set; } 
} 

public partial class Quote
{ 
    public virtual Book Book { get; set; }  
}

//Fluent Api 

modelBuilder.Entity<Quote>() 
    .HasOptional(b => b.Book); 

modelBuilder.Entity<Book>() 
    .HasMany<Quote>(s => s.Quotes) 
    .WithRequired(s => s.Book) 
    .HasForeignKey<int>(s => s.QuoteBookID);

You have written

modelBuilder.Entity<Quote>() 
    .HasOptional(b => b.Book); 

modelBuilder.Entity<Book>() 
    .HasMany<Quote>(s => s.Quotes) 
    .WithRequired(s => s.Book) 
    .HasForeignKey<int>(s => s.QuoteBookID);

Which describes a self-contradictory state of affairs. Quote.Book cannot be both required and optional so we must make up our mind.

If it is required then

modelBuilder.Entity<Book>() 
    .HasMany(s => s.Quotes) 
    .WithRequired(s => s.Book)
    .HasForeignKey(s => s.QuoteBookID);

is all that is necessary. We need not configure the optionality

Id it is optional then

modelBuilder.Entity<Book>() 
    .HasMany(s => s.Quotes) 
    .WithOptional(s => s.Book)
    .HasForeignKey(s => s.QuoteBookID);

Note that I've removed the explicit type arguments as they are unnecessary.

We can go a bit further in cleaning up and just write

modelBuilder.Entity<Book>() 
    .HasMany(s => s.Quotes) 
    .WithOptional() // or .WithRequired()
    .HasForeignKey(s => s.QuoteBookID);

As there's no need to be overly specific

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM