EF 4.3代码第一 - 如何设置默认值 [英] EF 4.3 code first - How to set default value

查看:147
本文介绍了EF 4.3代码第一 - 如何设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的实体:

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:


  • 创建零件时,默认的Section(Name =第1节)。这不能被删除。

创建新的文件没有问题,但是从数据库获取数据时,EF会创建一个默认的部分也将数据从DB添加到我的实体,所以是错误的。

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.

任何想法?谢谢

推荐答案

在实体创建时,没有傻瓜的方式来实现你所需要的。但是您可以在实体保存之前执行此操作。

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

这篇关于EF 4.3代码第一 - 如何设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆