EF 6 fluent api IsRequired attribute

青春壹個敷衍的年華 提交于 2020-01-06 14:54:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!