I have the following models:
Code: Select all
public abstract class IDObject
{
[Key]
public Guid ID { get; set; }
}
public class TV : IDObject
{
public TV()
{
this.Channels = new List<Channel>();
}
public string Name { get; set; }
public virtual IList<Channel> Channels { get; set; }
}
public class Channel : IDObject
{
public string Name { get; set; }
public int Number { get; set; }
[Navigational]
public virtual IList<TV> TVs { get; set; }
}
Now basically I want to be able to add a TV and a Channel to the database, dispose the context, have the TV reference the channel that has previously been added, then update the database entity.
Something like:
Code: Select all
TV someTV = new TV() { ID = Guid.NewGuid(), Name = "myBigTV" };
Channel chan1 = new Channel() { ID = Guid.NewGuid(), Name = "CBC", Number = 3};
using (ReferenceContext context = new ReferenceContext())
{
context.TVs.Add(someTV);
context.Channels.Add(chan1);
context.SaveChanges();
}
someTV.Name = "myBigTV updated";
someTV.Channels.Add(chan1);
using (ReferenceContext context = new ReferenceContext())
{
context.TVs.Attach(someTV);
context.Entry(someTV).State = EntityState.Modified;
*** some code here ***
context.SaveChanges();
}
Now I've tried .Load() on the DbCollectionEntry for Channels. I've tried removing all refs to channels from someTV in the context, then re-adding them. I've tried changing the EntityState on the channels I've referenced from someTV to Modified... and it seems like nothing works.
I'm using code first and the Database is creating the following tables for me:
Channels
ChannelTVs
TVs
Channels and TVs both look fine, but my join table 'ChannelTVs' is always empty regardless of what I do.
Question one: What is the standard way to update associations in this scenario. I don't need to necessarily update the Channels themselves, just basically add/remove entities from the join table. Do I need to add something to the fluent API to pick up these changes for me?
Question two: Is there any way to do this in a generic way? My current update sort of looks like:
Code: Select all
void Update<TDatabase>(IDatabaseContext context, TDatabase item)
{
IDbSet<TDatabase> dbSet = context.GetDbSet<TDatabase>();
dbSet.Attach(item);
context.Entry(item).State = EntityState.Modified;
context.SaveChanges();
}
Thanks.