AMS
AMS

Reputation: 439

SortedList of an Entity in Entity Framework Code First

I need to change a Many-to-Many relation ship in my project from List to a SortedList. I use Entity Framework 6 with Code First and Automatic Migration.

We have a new requirement which is to have an ordered list. I thought it would be pretty simple but it seems like the migration does not take in account my modification.

So I have to choose a alternative choice. So far I have some ideas but I'm not sure which is the best way.

I could add a propriety in AnEntity :

public int order {get; set;}

But I dont like this idea because I can have AnEntity in several list.

I could also make a new objet and change List<AnEntity> to List<AnEntityWithOrder>

public abstract class AnEntityWithOrder
{
    public int order {get; set;}
    public AnEntity AnEntity {get; set;}
}

I'm wondering if their might be performance issues.

At last I was wondering if It was possible to tell EF to create the ManyToMany table with an additionnal column for that order. Seems like it's not possible either. Do you know other ways for me to "simulate" this SortedList ???

Upvotes: 1

Views: 1735

Answers (1)

tschmit007
tschmit007

Reputation: 7800

Assuming I understand your need, you should create a new entity

before

class B {
}

class A {
    ICollection<B> Bs {get; set;}
}

modelBuilder.Entity<B>().HasMany(x => x.Bs).WithMany();

After

class B {
}

class C {
    int Order {get; set;}
    B B {get; set;}
    A A {get; set;}
}

class A {
    ICollection<C> Cs {get; set;}
}

modelBuilder.Entity<C>().HasRequired(x => x.B);
modelBuilder.Entity<C>().HasRequired(x => x.A).WithMany(y => y.Cs);

You can now sort Cs by Order

Upvotes: 3

Related Questions