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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With