I have a medias
table (for uploaded files), and many other tables which upload to this table.
Medias:
id, item_id, item_type, path
I want to have one-to-many relation between this table and others by item_id
and item_type
columns.
How should I define its ModelBuilder
in OnModelCreating
?
So when I say:
_db.Products.Include(x => x.Medias).FirstOrDefault(x => x.Id == 1)
it should select those medias with item_type
of product and item_id
of 1
CodePudding user response:
it should select those medias with "item_type" of product and "item_id" of 1
This is not a natural design for a relational database because there's no such thing as a "conditional foreign key". And EF is not going generate or leverage such a model.
If you create several many-to-many relationships, then EF will create several linking tables. You can make one of the FKs on a linking table unique if you want to model several one-to-many relationships.
CodePudding user response:
Fluent API for more details
example of one to many relationship
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasOne<Grade>(s => s.Grade)
.WithMany(g => g.Students)
.HasForeignKey(s => s.CurrentGradeId);
}
public DbSet<Grade> Grades { get; set; }
public DbSet<Student> Students { get; set; }