0

谁能告诉我下面这段代码有什么问题,因为我在获得一对一关系时遇到问题,首先使用 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

一直在尝试各种事情,添加外键属性,(取消)注释一些 id,以下示例。结果总是:数据库中的 ID 不正确,或者它没有创建数据库。

提前致谢。

4

1 回答 1

2

我没有 EF 4.3,但如果它在这方面与 EF 4.1 不同,那就令人惊讶了。我通过在 fluent API 中配置模型来完成它,在 DbContext 类中像这样覆盖 ModelBuilder:

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


// ...
}
于 2012-02-15T23:38:24.507 回答