我对EF代码优先有疑问。
我创建了两个POCO类和相应的映射类
public partial class Country
{
public Country()
{
this.Employees = new HashSet<Employee>();
this.States = new HashSet<State>();
}
public int CountryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<bool> Status { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
public virtual ICollection<State> States { get; set; }
}
internal partial class Country_Mapping : EntityTypeConfiguration<Country>
{
public Country_Mapping()
{
this.HasKey(t => t.CountryId);
this.ToTable("Country");
this.Property(t => t.CountryId).HasColumnName("CountryId");
this.Property(t => t.Name).HasColumnName("Name").IsUnicode(false).HasMaxLength(100);
this.Property(t => t.Description).HasColumnName("Description").IsUnicode(false).HasMaxLength(200);
this.Property(t => t.Status).HasColumnName("Status");
}
}
public partial class State
{
public State()
{
this.Employees = new HashSet<Employee>();
}
public int StateId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<int> CountryId { get; set; }
public Nullable<bool> Status { get; set; }
public virtual Country Country { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
internal partial class State_Mapping : EntityTypeConfiguration<State>
{
public State_Mapping()
{
this.HasKey(t => t.StateId);
this.ToTable("State");
this.Property(t => t.StateId).HasColumnName("StateId");
this.Property(t => t.Name).HasColumnName("Name").IsUnicode(false).HasMaxLength(100);
this.Property(t => t.Description).HasColumnName("Description").IsUnicode(false).HasMaxLength(200);
this.Property(t => t.CountryId).HasColumnName("CountryId");
this.Property(t => t.Status).HasColumnName("Status");
this.HasOptional(t => t.Country).WithMany(t => t.States).HasForeignKey(d => d.CountryId);
}
}
在Country
和State
课程中,Country
与State
之间没有导航关系。
但现在我想使用Include
实体框架声明来获取该国家的所有州。
UnityOfWork work = new UnityOfWork(new DbContextFactory<eSMSDbContext>());
var countryColl = work.GetRepository<Country>().Table.Include("State");
如何通过国家/地区获取州信息?
答案 0 :(得分:0)
如果没有从Country
类到State
类的导航属性,则Country对象没有任何变量来保存State
表的内容。实体框架只能将SQL信息映射到C#对象(如果存在)。
如果没有添加导航属性,您需要一个单独的变量(可能List<State)
)来保存State
个对象,不幸的是,您需要一个单独的Entity Framework调用来查找这些值,像
List<State> states = work.GetRepository<State>().Where(s => s.CountryId == countryId);
这有一个明显的缺点,即与Country
对象成为一个单独的对象,并且没有嵌套(List<Country>
无法保存与每个对应的List<State>