EF5流质映射一对一或一对一关系 [英] One to Zero or One relationship with EF5 fluent mapping

查看:248
本文介绍了EF5流质映射一对一或一对一关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个实体:

public class MainEntity()
{
    public long Id { get; set; }

    public long EntityAId { get; set; }
    public EntityA OptionalEntityA { get; set; }

    public long EntityBId { get; set; }
    public EntityB OptionalEntityB { get; set; }

    public string SProp { get; set; }
}

public class EntityA()
{
    public long Id { get; set; }

    public long MainEntityId { get; set; }
    public MainEntity RequiredEntity { get; set; }
}

public class EntityB()
{
    public long Id { get; set; }

    public long MainEntityId { get; set; }
    public MainEntity RequiredEntity { get; set; }
}

所有三个实体都有由数据库生成的自己的ID:

All three entities have there own Id generated by database:

Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

我如何定义MainEntity与EntityA和EntityB之间的关系,以便:

How can I define the Relationship between MainEntity and EntityA and EntityB in order to have:


  • MainEntity可能有零个或一个EntityA

  • MainEntity可能有零个或一个EntityB

  • EntityA必须具有一个MainEntity

  • EntityB必须具有一个MainEntity

  • MainEntity may have zero or one EntityA
  • MainEntity may have zero or one EntityB
  • EntityA must have one MainEntity
  • EntityB must have one MainEntity

MainEntityConfigurationMap我已经定义了这样的关系:

In my MainEntityConfigurationMap I have defined relation like this:

HasOptional(m => m.OptionalEntityA).WithRequired(ea => ea.RequiredEntity);
HasOptional(m => m.OptionalEntityB).WithRequired(eb => eb.RequiredEntity);

查看生成的迁移,我对EntityA有了这个

Looking at the generated migration I have this for EntityA:

        CreateTable(
            "dbo.EntityA",
            c => new
                {
                    Id = c.Long(nullable: false, identity: true),
                    MainEntityId = c.Long(nullable: false),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.MainEntity", t => t.Id)
            .Index(t => t.Id);

实体框架在此处定义了一个共享主键,有没有一种方法可以避免这种情况并使MainEntityId变成poiting

Entity Framework is defining a shared primary key here, is there a way to avoid that and make MainEntityId poiting to MainEntity.Id?

推荐答案

实体框架仅在共享主键(依赖项中的PK)上支持一对一关系表也​​是FK到主体表)。原因是从属表中的FK必须唯一以强制一对一关系,但EF当前不支持唯一约束(PK除外)。

Entity framework supports one-to-one relation only on top of shared primary key (PK in dependent table is also FK to principal table). The reason is that FK in dependent table must be unique to enforce one-to-one relation but EF currently doesn't support unique constraint (except PK).

这篇关于EF5流质映射一对一或一对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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