1

英孚 4.3.1。我已经定义了User实体Box。每个框可能分配给用户,也可能不分配给用户。
我想要实现的是在类中有一个OwnBox属性,在User类中有一个Owner属性Box
在数据库中,我OwnerIdBoxesBoxes.OwnerIdUsers.UserId)中定义了外键。
为了定义与 fluent api 的关系,我定义了以下类:

public partial class User
{
    public int UserId {get; set;}
    public virtual Box OwnBox { get; set; }
}

public partial class Box
{
    public int? OwnerId { get; set; }
    public virtual User User { get; set; }
}

然后在我的 Mapping 类中Box,我定义了如下关系:

this.HasOptional(t => t.User).WithOptionalDependent(d => d.OwnBox).
    Map(m => m.MapKey("OwnerId")).WillCascadeOnDelete(true);  

但是通过启动项目,我得到了错误:

指定的架构无效。错误:(56,6):错误 0019:类型中的每个属性名称必须是唯一的。已定义属性名称“OwnerId”。

所以我不得不告诉 EF 先忘记这个OwnerId专栏:

this.Ignore(t => t.OwnerId);  

现在项目运行良好。但是我仍然怀疑这是否是一种好方法,并且在具有外键关联的 CRUD 操作上一切正常。

4

1 回答 1

1

First of all, this is not one-to-one relationship. In one-to-one relationship the foreign key must be a primary key.

I believe in your scenario the situation can happen:

User = { UserID = 2 }

Box1 = { UserID = 2 }
Box2 = { UserID = 2 }

Nothing stops you from doing that, but which box should be returned when you do that: User.OwnBox, Box1 or Box2?

EF can deal with that using Independent Association. It will create foreign key, hidden from your POCO class. You can specify the name of the column using MapKey as you did. However, because you also created a property called OnwerID, just as the column used with MapKey, the EF has a problem as two properties are mapped to the same column.

When you use ignore, the POCO OwnerID property is ignored by EF so that fixes the problem of two properties, however, the OwnderID value never gets saved or read to the database. Because EF just ignores it.

Thanks for your question, I have learnt a lot thanks to this.

于 2013-04-30T19:46:20.220 回答