问题
I have two classes: address and city. I want city property to be required in address class, but when I add property(p => p.City).IsRequired() to fluent api I get error that City must non-nullable value type, but when I decorate City property with [Required] annotation everything works.
So how to do it with fluent api and why property(p => p.Street).IsRequired() works for string - string isn'e non-nullable value type
public class Address
{
public int AddressId { get; private set; }
public string Street { get; internal set; }
[Required]
public City City { get; internal set; }
}
public class CIty
{
public int CityId {get; private set; }
public string Name {get; internal set;}
}
回答1:
In order to specify the cardinality of a relationship, you need to use the HasRequired method instead -- the Property method is only used for scalar properties.
modelBuilder.Entity<Address>().HasRequired(a => a.City);
来源:https://stackoverflow.com/questions/19772327/ef-6-fluent-api-isrequired-attribute