为什么我的外键参考属性不反映外键ID属性值? [英] Why aren't my foreign key reference properties reflecting the foreign key ID property values?

查看:178
本文介绍了为什么我的外键参考属性不反映外键ID属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个候选人实体,下面列出了一些关联。我有一个视图模型,没有参考属性,只是外键属性,我使用AutoMapper将视图模型映射回实体。当我尝试并保存实体时,我得到验证错误告诉我,例如因为虽然我的 TitleId 有一个有效的值,但是 Title 是仍然为空。

I have a Candidate entity, with some associations exampled below. I have a view model that doesn't have the reference properties, just the foreign key properties, and I am using AutoMapper to map the view model back to an entity. When I try and save the entity, I get validation errors telling me that e.g. The Title field is required. because although my TitleId has a valid value, Title is still null.

public class Candidate
{
...
    [Required]
    public string RefNum { get; set; }

    [ForeignKey("TitleId")]
    [Required]
    public Title Title { get; set; }
    public Guid TitleId { get; set; }
...
}

PS,我可以看到必需属性在这里引起麻烦,但是我还要坚持TitleId必须是有效的ID,而不仅仅是一个空的Guid?

PS, I can see how the Required attribute is causing trouble here, but how else do I insist that TitleId must be a valid ID, not just an empty Guid?

推荐答案

删除 [必需] 属性。您的Guid不是空的,因为空的Guid {00000000-0000-0000-0000-000000000000} 是一个有效的Guid,它是一个有效的 uniqueidentifier 数据库中的列值。 ( Guid 是一个 struct ,不能为 null 。您有责任设定Guid的正确价值。因为 Guid 不为空,EF将根据需要检测关系。

Remove the [Required] attribute. It doesn't guarantee anyway that your Guid is not empty because an empty Guid {00000000-0000-0000-0000-000000000000} is a valid Guid which is a valid uniqueidentifier column value in the database. (Guid is a struct which cannot be null.) You are responsible to set the correct value of the Guid. Because the Guid is not nullable EF will detect the relationship as required anyway.

或者,您也可以关闭验证上下文实例...

Alternatively you can also turn off the validation for the context instance...

context.Configuration.ValidateOnSaveEnabled = false;

...以避免错误。您还可以在Fluent API( HasRequired / WithRequired )中配置映射,而不是使用数据注释来避免验证错误。

...to avoid the error. You can also configure the mapping in Fluent API (HasRequired/WithRequired) instead of using the data annotation to avoid the validation error.

这篇关于为什么我的外键参考属性不反映外键ID属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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