Reputation: 245
ASP.NET MVC4, C#.
I have two models A and B. They have a many-to-many relationship with each other.
Suppose A has a collection of B. I want to sort the collection of B on A and persist it in a database.
The correct database design for this is to add an additional property to the bridge table A_B. However, entity framework does not allow this. What is the best solution to allow sorting in entity framework for many-to-many relationships?
Thanks.
Upvotes: 1
Views: 1599
Reputation: 177133
You must model this with two one-to-many relationships instead of a single many-to-many. It means that you have to expose the bridge table as an entity in your model and this entity would have a SortOrder
property:
public class A_B
{
[Key, ForeignKey("A"), Column(Order = 1)]
public int AId { get; set; }
[Key, ForeignKey("B"), Column(Order = 2)]
public int BId { get; set; }
public A A { get; set; }
public B B { get; set; }
public int SortOrder { get; set; }
}
The entities A
and B
get collections not directly to each other but to this intermediate entity:
public class A
{
public int AId { get; set; }
public ICollection<A_B> A_Bs { get; set; }
}
public class B
{
public int BId { get; set; }
public ICollection<A_B> A_Bs { get; set; }
}
To save the relationship "in sorted order" you could then write for example:
var b1 = context.Bs.Find(1);
var b2 = context.Bs.Find(2);
var a = new A
{
A_Bs = new List<A_B>
{
new A_B { B = b1, SortOrder = 1 },
new A_B { B = b2, SortOrder = 2 }
}
};
context.As.Add(a);
context.SaveChanges();
Now, when you load the A
entity you can load the collection in that sort order:
var a = context.As.Find(1);
a.A_Bs = context.Entry(a).Collection(x => x.A_Bs).Query()
.Include(y => y.B)
.OrderBy(y => y.SortOrder)
.ToList();
Here are more details how to work with such a model that has additional data in the bridge table.
Upvotes: 8