简体   繁体   English

EF代码优先,同一表中带有2个非空外键

[英]EF code-first with 2 non-null Foreign Keys in the same table

I am using Entity Framework code first. 我首先使用实体​​框架代码。

I was trying to put 2 foreign keys on the same table but I am not being allowed to do so. 我试图将2个外键放在同一张桌子上,但不允许这样做。

It's like that(edited) : 就像那样(编辑):

The table is called Avaliacao : 该表称为Avaliacao

[Required]
public int AvaliacaoId { get; set; }


[Required]
public int LivroId { get; set; }
public int? AutorId { get; set; } 

public virtual Livro Livro { get; set; }
public virtual Autor Autor { get; set; }

I wanted AutorId not to be null but it only works that way. 我希望AutorId 不为null,但只能那样工作。

I wish I could have 2 non-nullable FK but only one Delete on Cascade . 我希望我可以有2个不可为空的FK,Delete on Cascade只有一个Delete on Cascade

How do I achieve this with Entity Framework code-first? 如何使用Entity Framework代码优先实现此目的?

Somebody help me please 有人帮我

thx in advance 提前

ZeCarioca ZeCarioca

EDIT: 编辑:

I have not tested this, but if you are using EF5 you could make use of the OnModelCreating method by overiding it in your DbContext. 我尚未对此进行测试,但是如果您使用的是EF5,则可以通过在DbContext中覆盖它来使用OnModelCreating方法。 You can call the same entity multiple times to add configuration so you could specify a second foreign key, set its HasRequired property and set its WillCascadeOnDelete property to true. 您可以多次调用同一实体以添加配置,因此您可以指定第二个外键,设置其HasRequired属性并将其WillCascadeOnDelete属性设置为true。

Something like this for the first foreign key. 第一个外键是这样的。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Avaliacao>()
                .HasRequired(a => a.LivroId)
                .HasForeignKey(m => a.LivroId)
                .WillCascadeOnDelete(false);

    modelBuilder.Entity<Avaliacao>()
                .HasRequired(a => a.AutorId)
                .HasForeignKey(m => a.AutorId)
                .WillCascadeOnDelete(false);

}

For more reference on the method you can look here at the MSDN Docs: DbModelBuilder 有关该方法的更多参考,请参见此处的MSDN文档: DbModelBuilder

As mentioned I have not tested this myself so you might need to change some of the properties. 如前所述,我自己尚未对此进行测试,因此您可能需要更改某些属性。

Hope it helps 希望能帮助到你

You can do this through the fluent API, for example: 您可以通过流畅的API来执行此操作,例如:

modelBuilder.Entity<MyEntity>().HasRequired(t => t.Livro);
modelBuilder.Entity<MyEntity>().HasRequired(t => t.Autor);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM