我用过这篇文章 [http://www.codeproject.com/Articles/615499/Models-POCO-Entity-Framework-and-Data-Patterns][1] 实现我的存储库模式:
例如,我有这个模型和repo实现:
public class Teacher
{
public Teacher()
{
this.Reshte = new Reshte();
this.City = new City();
this.Books = new HashSet<TeacherBook>();
}
public int ID { get; set; }
public string Name { get; set; }
public string Family { get; set; }
public string Tell { get; set; }
int CityID { get; set; }
public City City { get; set; }
public string Attend { get; set; }
public Reshte Reshte { get; set; }
int ReshteID { get; set; }
public bool Recruitment { get; set; }//True rasmi False gharardady
public DateTime Date { get; set; }
public virtual ICollection<TeacherBook> Books { get; set;}
}
public class TeacherBook
{
public int ID { get; set; }
public int TeacherID { get; set; }
public int BookID { get; set; }
public virtual Teacher Teacher { get; set; }
public virtual Book Book { get; set; }
public string Day { get; set; }
}
public interface IRepository<T> where T :class
{
IQueryable<T> GetAll();
T GetByID(int id);
void ADD(T entity);
void Update(T entity);
void Delete(T entity);
void Delete(int ID);
}
public class Repository<T>:IRepository<T> where T:class
{
protected DbContext DbContext{ get; set; }
protected DbSet<T> DbSet { get; set; }
public Repository(DbContext dbContext)
{
if (dbContext!=null)
{
DbContext = dbContext;
DbSet = DbContext.Set<T>();
}
}
public IQueryable<T> GetAll()
{
return DbSet.ToList().AsQueryable();
}
public T GetByID(int id)
{
return DbSet.Find(id);
}
public virtual void ADD(T entity)
{
var res = DbContext.Entry(entity);
if (res.State != System.Data.EntityState.Detached)
{
res.State = System.Data.EntityState.Added;
}
else
DbSet.Add(entity);
}
public void Update(T entity)
{
DbEntityEntry res = DbContext.Entry(entity);
if (res.State != System.Data.EntityState.Detached)
{
DbSet.Attach(entity);
}
res.State = System.Data.EntityState.Modified;
}
public void Delete(T entity)
{
DbEntityEntry res = DbContext.Entry(entity);
if (res.State!=System.Data.EntityState.Deleted)
{
res.State = System.Data.EntityState.Deleted;
}
else
{
DbSet.Attach(entity);
DbSet.Remove(entity);
}
}
public void Delete(int ID)
{
var res = GetByID(ID);
if (res == null)
return;
else
Delete(res);
}
}
public class TeacherBookRepository:Repository<TeacherBook>,ITeacherBookRepository
{
public TeacherBookRepository(System.Data.Entity.DbContext DbContext):base(DbContext)
{
}
public IEnumerable GetTeacherBookList()
{
return GetAll().Select(x => new {ID=x.ID,BookName=x.Book.Name,Day=Day(x.Day), }).ToList();
}
private object Day(string p)
{
//...
}
}
当我想要检索数据时,导航属性的相关数据为空。例如
在GetTeacherBookList
方法的结果中,bookName为null。
如何解决这个问题?