首先使用代码(EF 6),我创建了1个父亲 - 2子关系。属性是父对象,属性地址为具有1或0..1关系的子对象。 PropertyImage是另一个有1对多关系的孩子。 PropertyImage工作正常,但如果我尝试加载,PropertyAddress会抛出错误。
实际错误 -
违反了多重性约束。 “MyAssetTracker.DataLayer.Models.PropertyAddress_Property”关系的“PropertyAddress_Property_Source”角色具有多重性1或0..1。
// Test Function
GetProperty()
{
Property property;
using (var repo = new PropertyRepository())
{
property = repo.AllIncluding(a=>a.Images, a=>a.Address).FirstOrDefault(a => a.Id == testpropertyid);
}
}
//Property Repository
public class PropertyRepository : IPropertyRepository
{
public IQueryable<Property> AllIncluding(params Expression<Func<Property, object>>[] includeProperties)
{
IQueryable<Property> query = context.Properties;
foreach (var includeProperty in includeProperties) {
query = query.Include(includeProperty);
}
return query;
}
}
//Property Entity
public class Property : DomainModelAuditBase, IDomainModelState
{
private Address _address;
private ICollection<Asset> _assets;
private ICollection<PropertyImage> _images;
public Property()
{
_address = new Address();
_assets = new List<Asset>();
_images = new List<PropertyImage>();
}
public Guid Id { get; set; }
[StringLength(100), Required]
public string Title { get; set; }
public bool IsPrimary { get; set; }
[StringLength(255)]
public string Description { get; set; }
[NotMapped]
public State State { get; set; }
public Guid AddressId { get; set; }
public Guid UserId { get; set; }
public virtual Address Address
{
get { return _address; }
set { _address = value; }
}
public virtual ICollection<Asset> Assets
{
get { return _assets; }
set { _assets = value; }
}
public virtual User User { get; set; }
public virtual ICollection<PropertyImage> Images
{
get { return _images; }
set { _images = value; }
}
}
//PropertyAddress
public class Address : DomainModelAuditBase, IDomainModelState
{
[Key,ForeignKey("Property")]
public Guid PropertyId { get; set; }
[StringLength(255),Required]
public string AddressLine1 { get; set; }
[StringLength(255)]
public string AddressLine2 { get; set; }
[StringLength(255)]
public string City { get; set; }
[StringLength(255)]
public string StateProvince { get; set; }
[StringLength(100)]
public string PostalCode { get; set; }
[StringLength(100)]
public string Country { get; set; }
[NotMapped]
public State State { get; set; }
public virtual Property Property { get; set; }
}
答案 0 :(得分:7)
从Property构造函数中删除_address = new Address();
。
You could read about similar problem here
您还确定在Property类中需要AddressId字段吗?