How does one map a junction table with values in EF v6.2?
Let's say you have entities named "Item1", "Item2" and another entity of them mapped:
public class Item1
{
[Key]
public long Id { get; set; }
public virtual ICollection<MapItem> { get; set; }
}
public class Item2
{
[Key]
public int Id { get; set; }
public virtual ICollection<MapItem> { get; set; }
}
public class MapItem
{
public long Item1ID {get; set;} //PK, FK
public int Item2ID {get; set;} //PK, FK
public decimal Value {get; set;}
public string Name {get; set;}
public virtual Item1 {get; set;}
public virtual Item2 {get; set;}
}
EDMX automatically generates this but how would I build this with code-first / FluentAPI to build an accessible collection of the MapItem
entity?
I've tried updating the mapped entity to use [Key(Order = 1)]
and [Key(Order = 2)]
on the PK & FK values for MapItem
.
This seems like a weird scenario considering it's not a true junction table of 2 entities, but also holds value as well.
Here I was able to get it resolved using FluentAPI.
Here I modified the entity class:
public class MapItem
{
[Key(Order = 1)]
public long Item1ID {get; set;} //PK, FK
[Key(Order = 2)]
public int Item2ID {get; set;} //PK, FK
public decimal Value {get; set;}
public string Name {get; set;}
public virtual Item1 {get; set;}
public virtual Item2 {get; set;}
}
Then in the relationship builder:
modelBuilder.Entity<MapItem>().HasKey(q => new
{
q.Item1ID, q.Item2ID
});
modelBuilder.Entity<MapItem>().HasRequired(q => q.Item1).WithMany(q => q.MapItem).HasForeignKey(q => q.Item1ID);
modelBuilder.Entity<MapItem>().HasRequired(q => q.Item2).WithMany(q => q.MapItem).HasForeignKey(q => q.Item2ID);
The crucial part was the "HasKey" method which correctly mapped the entities.
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.