Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 7 beta 6 : Entities with one to many relationships in EF 7

I have a very simple model:

class Bag
{
    public int Id { get; set; }
    public ICollection<RandomThing> RandomThings { get; set; }
}

class RandomThing
{
    public int Id { get; set; }
    public String Description{ get; set; }
}

My context's OnModelCreating (in EF 6) is something like:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Bag>()
        .ToTable("Bag")
        .HasMany(x => x.RandomThings).WithRequired(x => x.Bag).WillCascadeOnDelete();

    modelBuilder.Entity<RandomThing>().ToTable("RandomThing");
}

As far as I can tell, there is no equivalent way to do this. I know that cascade deletes are not supported. However, I was wondering, what is the best way to model the one to many relationships as defined in my code example? It seems like all of that stuff has gone (or is yet to be implemented).

I have seen an example (here) of a DbContext exactly like how I want, but it's actually wrong and doesn't work. If I try to pull down that source code, set up my environment, and do a save on a blog entity with posts, those posts don't get saved as one might imagine.

Are there any workarounds for this?

like image 631
Lutando Avatar asked Aug 11 '15 13:08

Lutando


1 Answers

Update: This answer was written for EF7 beta7. APIs have since changed. See http://docs.efproject.net/en/latest/modeling/relationships.html for the latest on using EF Core.

Original Answer

In EF 7, you can configure one to many relationships in the OnModelCreating method. For this to work, add a property to RandomThing to represent the forign key, and also a CLR reference to the parent type.

class Bag
{
    public int Id { get; set; }
    public ICollection<RandomThing> RandomThings { get; set; }
}

class RandomThing
{
    public int Id { get; set; }
    public String Description{ get; set; }

    public Bag Bag { get; set; }
    public int BagId { get; set; }
}

In your context, configure the relationship with the following setup:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{  
    modelBuilder.Entity<RandomThing>()
        .Reference(e => e.Bag)
        .InverseCollection(p => p.RandomThings)
        .ForeignKey(e => e.BagId);
}

Side note: When EF 7 plans to add support for configuring this via attributes instead.

like image 53
natemcmaster Avatar answered Sep 28 '22 04:09

natemcmaster