单向一比一的关系在实体框架 [英] Unidirectional One-To-One relationship in Entity Framework

查看:178
本文介绍了单向一比一的关系在实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面实施例的一对一关系而引发异常

Below example of one-to-one relationship throws an exception

public class User
{
    public int Id { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public int Id { get; set; }
    public User User { get; set; }
}

异常说:

无法确定之间的关联的主要结束   类型ConsoleApplication1.Address'和'ConsoleApplication1.User。   该协会的主要端必须明确配置   无论使用的关系流利的API或数据注解。

Unable to determine the principal end of an association between the types 'ConsoleApplication1.Address' and 'ConsoleApplication1.User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

它的工作原理,如果我的地址删除用户属性,但我不想。

it works if i remove User property from Address but i don't want.

我怎么能有没有例外,这样的关系?

How can i have such a relationship without an exception ?

推荐答案

虽然由Eranga提供的答案是正确的,并创建一个<一个href="http://weblogs.asp.net/manavi/archive/2011/04/14/associations-in-ef-4-1-$c$c-first-part-3-shared-primary-key-associations.aspx">shared用户和地址之间的主键关联,你可能不希望使用它,由于这种映射类型具有局限性。

While the answer provided by Eranga is correct and creates a shared primary key association between User and Address, you might not want to use it due to the limitations this mapping type has.

下面是创建一个1的另一种方式:1的关联被称为<一个href="http://weblogs.asp.net/manavi/archive/2011/05/01/associations-in-ef-4-1-$c$c-first-part-5-one-to-one-foreign-key-associations.aspx">one-to-one外键关联:

Here is another way of creating a 1:1 association which is called one-to-one foreign key association:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Address>()
                .HasRequired(a => a.User)
                .WithOptional(u => u.Address)
                .Map(m => m.MapKey("UserId"));
}

EF code首先认识到这是一个1:1的关联,因此可以让您拥有用户和地址之间的双向联系。

EF Code First recognizes this as a 1:1 association hence allowing you to have a bidirectional association between User and Address.

现在,所有你需要做的就是定义的用户ID列的唯一键约束,使你们的关系一个真实的,以一个在数据库端。这样做的一个方法是使用已在自定义初始化类被覆盖的种子的方法:

Now all you need to do is to define a Unique Key constraint on the UserId column to make your relationship a true one to one on your database side. One way for doing so is using a Seed method that has been overridden in a custom initializer class:

class DbInitializer : DropCreateDatabaseAlways<Context>
{
    protected override void Seed(Context context)
    {
        context.Database.ExecuteSqlCommand("ALTER TABLE Addresses ADD CONSTRAINT uc_User UNIQUE(UserId)");
    }
}


上述code会导致以下模式:


The above code will result in the following schema:

这篇关于单向一比一的关系在实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆