【发布时间】:2016-09-24 03:33:53
【问题描述】:
我的问题很简单:这里我有两个具有一对多关系的类。 让我们举个例子: 样本取自 Julia Lerman “Programming Entity Framework : Code First”一书
public class Destination
{
public int DestinationId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Description { get; set; }
public byte[] Photo { get; set; }
public ICollection<Lodging> Lodgings { get; set; }
public Destination()
{
Lodgings = new List<Lodging>();
}
}
public class Lodging
{
public int LodgingId { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public bool IsResort { get; set; }
public decimal MilesFromNearestAirport { get; set; }
public Destination Destination { get; set; }
public int DestinationId { get; set; }
}
这里使用 FluentApi 进行配置:
public class LodgingConfiguration : EntityTypeConfiguration<Lodging>
{
public LodgingConfiguration()
{
Property(p => p.Name).IsRequired().HasMaxLength(200);
HasRequired(p => p.Destination).WithMany(p => p.Lodgings);
}
}
public class DestinationConfiguration : EntityTypeConfiguration<Destination>
{
public DestinationConfiguration()
{
Property(p => p.Name).IsRequired().HasMaxLength(100);
Property(p => p.Description).HasMaxLength(500);
Property(p => p.Photo).HasColumnType("image");
HasMany(p=>p.Lodgings).WithRequired(l=>l.Destination);
}
}
我猜那几行
HasRequired(p => p.Destination).WithMany(p => p.Lodgings);
和
HasMany(p=>p.Lodgings).WithRequired(l=>l.Destination);
在 Destination 和 Lodging 之间的关系上提供相同的结果。
如果我只定义其中一个规则,它也很有效。 在双方都定义相同的规则是一种好习惯还是一方声明可以?
【问题讨论】:
标签: c# entity-framework