多重约束违规使用可选要求的EF代码优先

多重约束违规使用可选要求的EF代码优先

本文介绍了多重约束违规使用可选要求的EF代码优先+流利的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,我有我做了我的脑海而回上EF 6项目,我会尽量避免命名外键。我定义在模型的大部分不增量测试它,所以我一直运行到多重性和不完全流利的API定义问题:



In one case, here is the code:

nModelBuilder.Entity<User>()
    .HasOptional<InternalAuth>(u => u.InternalAuth)
    .WithRequired(a => a.User)
    .WillCascadeOnDelete(true);

My understanding is that it is saying:

  • The entity User
  • Has an optional property InternalAuth of type InternalAuth
  • On the other end, InternalAuth has a required property User, so that all InternalAuths have Users but Users may or may not have an `InternalAuth.
  • If the User gets deleted, so does his InternalAuth if he has one (does this override an optional behavior of treating optionals like nullables?)

However when I try to delete a User I receive an exception about the multiplicity of some association between InternalAuth and User.

  1. Is it true that if EF understands the multiplicity of a relationship there is a way for it to provide it a unique column name for it so there is a canonical naming convention?

  2. If so, do you ever really need to define foreign keys explicitly by annotating the model or through Fluent API?

  3. If not, is it a worthwhile or advisable thing that I should keep trying to avoid it? (I'm thinking along the lines of migrating the data model, database administration, any EF quirks)

  4. Why does attempting to delete the relationship above violate a multiplicity constraint? What else does it need to know?

解决方案

assuming that

My guess is the following : the FK is nullable so the fact to set it to null with the required constraint causes the rise of the exception.

One solution is to put the FK in the PK, that is add, in InternalAuth, the FK to User in the PK. Doing this will mark the entity as deleted when setting a part of his PK to null.

这篇关于多重约束违规使用可选要求的EF代码优先+流利的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:48