EF 4.3代码首先是一对一的关系

时间:2012-02-15 16:06:57

标签: c# asp.net-mvc-3 database-relations entity-framework-4.3

有人能告诉我下面这段代码有什么问题,因为我在使用EF 4.3代码时遇到一对一的关系时遇到了问题。

    // Problem with EF 4.3 code first, one-to-one relation

// context
// ------------
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{      
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

    modelBuilder.Entity<SecondModel>().HasRequired(r => r.FirstModel).WithOptional(r => r.SecondModel).WillCascadeOnDelete(false);
}


// models
// --------

public abstract class MyBaseEntity : // some interfaces
{
    // ...

    [EdmScalarPropertyAttribute(EntityKeyProperty = true, IsNullable = false)]
    public virtual int Id
    {
        get { return GetPropertyValue<int>("Id"); }
        set { SetPropertyValue<int>("Id", value); }
    }

    // ...
}

public class FirstModel : MyBaseEntity
{
    // ...

    public int SecondModelID { get; set; }
    public virtual SecondModel SecondModel { get; set; }

    // ...
}

public class SecondModel : MyBaseEntity
{
    // ...

    public int FirstModelID
    {
        get { return GetPropertyValue<int>("FirstModelID"); }
        set { SetPropertyValue<int>("FirstModelID", value); }
    }
    public virtual FirstModel FirstModel { get; set; }

    // ...
}

// this code above doesn't seem to work :s
// when removing FirstModelID and removing SecondModelID i'm unable to create the the database

一直在尝试各种各样的事情,添加foreignkey属性,(un)评论一些id,跟随样本。 结果总是:数据库中的ID不正确或者不创建数据库。

提前致谢。

1 个答案:

答案 0 :(得分:2)

我没有EF 4.3,但如果在这方面与EF 4.1不同,那就太令人惊讶了。我已经通过在流畅的API中配置模型来完成它,在DbContext类中重写了这样的模型构建器:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         modelBuilder.Entity<FirstModel>()
            .HasRequired(e => e.SecondModel)
            .WithRequiredPrincipal()
            .WillCascadeOnDelete(true);

            base.OnModelCreating(modelBuilder);

    }

班级:

public class FirstModel : MyBaseEntity
{
// ...

public virtual SecondModel SecondModel { get; set; }

// ...
}

public class SecondModel : MyBaseEntity
{
// ...

public int Id
{
    get { return GetPropertyValue<int>("FirstModelID"); }
    set { SetPropertyValue<int>("FirstModelID", value); }
}


// ...
}