问题描述
由于某种原因,我有我做了我的脑海而回上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 typeInternalAuth
- On the other end,
InternalAuth
has a required propertyUser
, so that allInternalAuth
s haveUser
s butUser
s may or may not have an `InternalAuth. - If the
User
gets deleted, so does hisInternalAuth
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
.
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?
If so, do you ever really need to define foreign keys explicitly by annotating the model or through Fluent API?
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)
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代码优先+流利的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!