Phuc
Phuc

Reputation: 489

EF 4.3 code first - How to set default value

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:

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

Upvotes: 0

Views: 1251

Answers (1)

Eranga
Eranga

Reputation: 32437

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();
    }
}

Upvotes: 1

Related Questions