如何使用实体框架代码首先定义一对一的自引用 [英] How to define a one to one self reference using Entity Framework Code First

查看:91
本文介绍了如何使用实体框架代码首先定义一对一的自引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的实体 上实现版本控制。每个实体都有对下一个版本的可选引用(最新版本将为null)和对先前版本的可选引用(第一个版本将为null)。我使用实体框架6,代码第一。我尝试使用以下模型和modelbuilder语句(和许多变体)。

I want to implement versioning on my entity Stuff. Each entity has an optional reference to the next version (the latest version will be null) and an optional reference to the previous version (the first version will be null). I am using entity framework 6, code first. I tried with the following model and modelbuilder statement (and many variations).

public class Stuff
{
    public int StuffId { get; set; }

    [ForeignKey("NextVersion")]
    public int? NextVersionId { get; set; }
    [InverseProperty("PreviousVersion")]
    public virtual Stuff NextVersion { get; set; }

    public virtual Stuff PreviousVersion { get; set; }
}

modelBuilder.Entity<Stuff>().HasOptional(t => t.NextVersion).WithOptionalDependent(t => t.PreviousVersion);

但是在这种情况下,[ForeignKey(NextVersion)]被忽略,外键NextVersion_StuffId是产生。如何指示EF使用属性NextVersionId作为外键?

However in this case the [ForeignKey("NextVersion")] is ignored and a foreign key NextVersion_StuffId is generated. How can I instruct EF to use the property NextVersionId as the foreign key?

推荐答案

public class Stuff
{
    public int Id { get; set; }

    public int? NextVersionId { get; set; }

    public int? PrevVersionId { get; set; }

    public virtual Stuff NextVersion { get; set; }

    public virtual Stuff PrevVersion { get; set; }

}

更新:

modelBuilder.Entity<Stuff>().HasOptional(t => t.NextVersion).WithMany().HasForeignKey(t => t.NextVersionId);
modelBuilder.Entity<Stuff>().HasOptional(t => t.PrevVersion).WithMany().HasForeignKey(t => t.PrevVersionId);

这篇关于如何使用实体框架代码首先定义一对一的自引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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