我使用Code First和Repository模式
实体:
public class Company : BaseEntity
{
private ICollection<CompanyRole> _companyRoles;
private ICollection<Branch> _branches;
public string Name { get; set; }
public int CityId { get; set; }
public virtual ICollection<CompanyRole> CompanyRoles
{
get { return _companyRoles ?? (_companyRoles = new List<CompanyRole>()); }
protected set { _companyRoles = value; }
}
public virtual ICollection<Branch> Branches
{
get { return _branches ?? (_branches = new List<Branch>()); }
protected set { _branches = value; }
}
public virtual City City { get; set; }
}
FluentApi映射:
public class CompanyConfiguration : EntityTypeConfiguration<Company>
{
public CompanyConfiguration()
{
this.ToTable("Company");
this.HasKey(c => c.Id);
this.Property(c => c.Name).HasMaxLength(100).IsRequired();
this.HasRequired(c => c.City)
.WithMany()
.HasForeignKey(c => c.CityId)
.WillCascadeOnDelete(false);
this.HasMany(v => v.CompanyRoles)
.WithMany()
.Map(m => m.ToTable("Company_CompanyRole_Mapping"));
}
}
public class BranchConfiguration : EntityTypeConfiguration<Branch>
{
public BranchConfiguration()
{
this.ToTable("Branch");
this.HasKey(c => c.Id);
this.Property(c => c.Name).HasMaxLength(100).IsRequired();
this.HasRequired(c => c.Company)
.WithMany()
.HasForeignKey(c => c.CompanyId);
}
}
存储库:
public class EFRepository<T> : IRepository<T> where T : class
{
public EFRepository(DbContext dbContext)
{
if (dbContext == null)
throw new ArgumentNullException("dbContext");
DbContext = dbContext;
DbSet = DbContext.Set<T>();
}
protected DbContext DbContext { get; set; }
protected DbSet<T> DbSet { get; set; }
public virtual IQueryable<T> GetAll()
{
return DbSet;
}
public virtual T GetById(int id)
{
return DbSet.Find(id);
}
}
当我使用方法GetById时,它返回我公司,但CompanyRoles,Branches和City为空(但CityId有值)。预计GetById方法将返回具有相关关系的实体。
答案 0 :(得分:0)
我在我的项目中使用了类似的模式。当我创建存储库时,我需要扩展通用存储库的任何方法,我更喜欢:
public class CompanyRepository : EFRepository<Company>, ICompanyRepository
然后实现方法GetCompany
public Company GetCompany(int id)
{
return this.DbContext.Set<Company>()
.Include(a => a.CompanyRoles)
.Include(a => a.Branches)
.SingleOrDefault(a => a.Id == id);}
其他方法是在接收实体后手动加载集合:
public Company GetCompany(int id)
{
var company = this.GetById(id);
this.DbContext.Entry(company).Collection(a => a.CompanyRoles).Load();
this.DbContext.Entry(company).Collection(a => a.Branches).Load();
return company;
}