问题
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, 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?
回答1:
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;
...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.
来源:https://stackoverflow.com/questions/9787396/why-arent-my-foreign-key-reference-properties-reflecting-the-foreign-key-id-pro