[英]EF 4.3 code first one-to-one relations
Could anybody tell me what's wrong with this code below, because I'm having problems getting an one-to-one relation working with EF 4.3 code first. 谁能告诉我下面这段代码有什么问题,因为我在首先使用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
Have been trying all kinds of things, adding foreignkey attributes, (un)commenting some id's, following samples. 在示例之后,尝试了各种尝试,添加外键属性,(取消)对某些ID的注释。 Results were always: IDs in database are not correctly or it doesn't create the database.
结果总是:数据库中的ID不正确或它没有创建数据库。
Thanks in advance. 提前致谢。
I dont have EF 4.3 but it is surprising if it is different from EF 4.1 in this regard. 我没有EF 4.3,但是在这方面与EF 4.1有所不同是令人惊讶的。 I've done it by configuring the model in the fluent API, overriding the ModelBuilder like this inside the DbContext class:
我通过在fluent API中配置模型,在DbContext类中重写ModelBuilder来做到这一点:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<FirstModel>()
.HasRequired(e => e.SecondModel)
.WithRequiredPrincipal()
.WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
And the classes: 和类:
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); }
}
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.