EF 4.3 code first - How to set default value

给你一囗甜甜゛ 提交于 2020-01-06 14:19:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!