我有一个名为Tour
的实体,可以有很多Agents
。我可以添加代理,但我无法删除它们。
// _repo is injected....
var tour = _repo.GetById(tourId);
tour.AddAgent(new Agent(tour.TourId));
当我尝试调用Tour.RemoveAgent()
方法时,实际上没有删除任何内容。我在Tour.RemoveAgent()
方法中设置了一个断点,我看到_agents
属性的计数为0
。
tour.RemoveAgent(agentId); // This doesn't work because _agents is empty
当我从我的存储库中检索_agents
时,是否必须为EF填充Tour
属性做一些特殊的事情?
我决定只为每个聚合创建一个唯一的存储库,这样就可以很容易地使用Include()
函数准确定义需要包含的内容。这是我从GenericRepository<T>
类继承的示例(也包含在此问题的底部)。
public class TourRepository : GenericRepository<Tour>
{
public TourRepository(IDatabaseFactory databaseFactory) : base (databaseFactory)
{
}
public override Tour GetById(Guid id)
{
return dataContext.Tours
.Include(x => x.Agents)
.Single(x => x.TourId == id);
}
}
旅游类
public partial class Tour
{
public Guid TourId { get; private set; }
protected virtual List<Agent> _agents { get; set; }
public Tour()
{
TourId = Guid.NewGuid();
_agents = new List<Agent>();
}
public void AddAgent(Agent agent)
{
_agents.Add(agent);
}
public void RemoveAgent(Guid agentId)
{
_agents.RemoveAll(a => a.AgentId == agentId);
}
}
代理类
public partial class Agent
{
public Guid AgentId { get; private set; }
public Guid TourId { get; private set; }
public Tour Tour { get; private set; }
public Agent(Guid tourId)
{
TourId = tourId;
AgentId = Guid.NewGuid();
}
}
OnModelCreating
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// AGENTS ============================
modelBuilder.Entity<Agent>()
.HasKey(x => x.AgentId)
.Property(p => p.AgentId);
modelBuilder.Entity<Agent>()
.HasRequired(p => p.Tour)
.WithMany(t => t.Agents);
// TOURS =============================
modelBuilder.Entity<Tour>()
.HasKey(x => x.TourId)
.Property(x => x.TourId);
}
存储库类
public class GenericRepository<T> : IRepository<T> where T : class {
private MyContext dataContext;
private readonly IDbSet<T> dbset;
public GenericRepository(IDatabaseFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
dbset = DataContext.Set<T>();
}
protected IDatabaseFactory DatabaseFactory
{
get;
private set;
}
protected MyContext DataContext
{
get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
}
// ... stuff removed for brevity ...
public T GetById(Guid id)
{
return dbset.Find(id);
}
}
答案 0 :(得分:7)
尝试制作受保护的虚拟列表_agents {get;组;公共
public virtual List<Agent> _agents { get; set; }
你也可以通过这样的方式来加载:
_databaseContext.Tours.Include(x => x.Agents).Single(x => x.TourId == tourId)