繁体   English   中英

为实体框架导航属性设置默认对象

[英]Setting a default object for Entity Framework navigation property

是否可以为实体设置默认对象?

假设我有一个Person实体,它最初对Profile没有要求。

现在我需要一个Profile - 但是存在当前没有Profile现有实体。

有没有办法在将来加载这些实体时为这些实体提供默认对象,因此任何使用Person实体的Person都可以假设Profile永远不会为 null 并且始终具有值 - 即使它是默认值。

下面你可以看到我尝试过的东西——它确实创建了一个默认值——但即使数据库中有东西,它也总是返回默认对象。

  • 如果Profilenull我想返回一个默认的初始化对象
  • 如果Profile不为null我想从数据库中返回对象

另外 - 将“默认”对象附加到我的 dbcontext 的最明智的方法是什么?

我怎样才能实现这种理想的行为?

public class Person
{
    [Key]
    public int Id {get; set;}

    private Profile _profile;
    public virtual Profile Profile
    {
        get
        {
            return _profile ?? (_profile= new Profile
            {
                Person = this,
                PersonId = Id
            });
        }
        set
        {
            _profile = value;
        }

        // properties
    }
}

public class Profile
{
    [Key, ForeignKey("Person")]
    public int PersonId {get; set;}

    [ForeignKey("PersonId")]
    public virtual Person Person{ get; set; }

    // properties
}

我知道您可以初始化集合以使它们不为空,但我也想初始化一个对象。

使用ObjectContext.ObjectMaterialized 事件

为实现后加载到上下文中的每个实体引发此事件。

在上下文的构造函数中,订阅此事件。 在事件处理程序中,检查实体类型是否为Person ,如果是,则为该人创建新配置文件。 这是一个代码示例:

public class Context : DbContext
{
    private readonly ObjectContext m_ObjectContext;

    public DbSet<Person> People { get; set; }
    public DbSet<Profile> Profiles { get; set; }

    public Context()
    {
        var m_ObjectContext = ((IObjectContextAdapter)this).ObjectContext;

        m_ObjectContext.ObjectMaterialized += context_ObjectMaterialized;

    }

    void context_ObjectMaterialized(object sender, System.Data.Entity.Core.Objects.ObjectMaterializedEventArgs e)
    {

        var person = e.Entity as Person;

        if (person == null)
            return;

        if (person.Profile == null)
            person.Profile = new Profile() {Person = person};

    }
}

请注意,如果您提交更改,新配置文件将保存回数据库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM