How to configure many to many relationship using entity framework fluent API
modelBuilder.Entity<Account>()
.HasMany(a => a.Products)
.WithMany()
.Map(x =>
{
x.MapLeftKey("Account_Id");
x.MapRightKey("Product_Id");
x.ToTable("AccountProducts");
});
ManyToMany Relation in EF Core fluent API
You need to use some of the other UsingEntity
overloads which allow you to configure the left and right navigations.
For instance
entityTypeBuilder1
.HasMany(lambdaManyFirst)
.WithMany(lambdaManySecond)
.UsingEntity<Dictionary<string, object>>(joinEntityName,
j => j.HasOne<TEntity2>().WithMany().HasForeignKey(fkName2),
j => j.HasOne<TEntity1>().WithMany().HasForeignKey(fkName1),
j => j.ToTable(joinTableName)
);
How Configure one to Many Relationship From AspNetUsers Table To ... using Fluent API
add relations
public class AppUser : IdentityUser
{
public string DisplayName { get; set; }
public string Bio { get; set; }
public virtual ICollection<Sale> Sales { get; set; }
}
}
public class Sale
{
public int SaleID { get; set; }
public int SaleAmount { get; set; }
public int UserID { get; set; }
public virtual AppUser User { get; set; }
}
Since you are using net core 5 you don't need any fluent apis in this case
but if you use another version you can add
modelBuilder.Entity<Sale>(entity =>
{
entity.HasOne(d => d.User)
.WithMany(p => p.Sales )
.HasForeignKey(d => d.UserId);
});
How to use Fluent API for creating a simple one-to-many relationship
The simple answer to your last question. EF is recognizing that Area.Id
is a primary key so connects Location.AreaId
to Area.Id
Also, here is a simple guide on how to do it.
Related Topics
How to Terminate a Thread in C#
How to Know the Repeating Decimal in a Fraction
Show Authentication Dialog in C# for Windows Vista/7
How to Generate a 3-D Surface from Isolines
How to Query for an Event Log Details with a Given Event Id
Is Deferred Execution in ASP.NET MVC View a Very Bad Thing
Mocking Static Methods Using Rhino.Mocks
Selecting Attribute Values with HTML Agility Pack
Improving/Fixing a Regex for C Style Block Comments
Sqlite .Net Performance, How to Speed Up Things
Why Does My .Net Application Crash When Run from a Network Drive
What Would Be the Fastest Way to Concatenate Three Files in C#
How to Sync the Scrolling of Two Multiline Textboxes
How to Disable Aero Snap in an Application
Adding Multiple Icons (Win32-Resource) to .Net-Application
Datagrid Column Width Doesn't Auto-Update