问题
I'm having an entity like that:
public class Part : Entity
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<VersionSection> VersionSections
{
get
{
return Sections.Where(s => s is VersionSection).Cast<VersionSection>();
}
}
public virtual ICollection<Section> Sections { get; set; }
public Part()
{
this.Sections = new List<Section>();
}
}
I would like to set the default value for the Sections collection very time when I create a new instance of Part following to this business:
- When creating a Part, a default Section (Name = "Section 1") should be created. This cannot be deleted.
There's no problem on creating a new one, but when getting data from DB, EF create a default instance of Section and also add the data from DB to my entity, so it's wrong.
Any ideas? Thanks
回答1:
There is no fool proof way to achieve what you need at the time of entity creation. However you can do this before the entity gets saved.
public class MyContextTest : DbContext
{
public override int SaveChanges()
{
var parts = ChangeTracker.Entries<Part>()
.Where(e => e.State == System.Data.EntityState.Added)
.Select(e => e.Entity);
foreach (var item in parts)
{
if (item.Sections == null)
item.Sections = new List<Section>();
item.Sections.Add(new Section { Name = "Section 1" });
}
return base.SaveChanges();
}
}
来源:https://stackoverflow.com/questions/10135058/ef-4-3-code-first-how-to-set-default-value