簡體   English   中英

實體框架存儲庫模式創建或更新多對多

[英]Entity Framework repository pattern create or update many to many

我知道有很多關於此的主題,但是我在插入和更新與Entity Framework 6的許多關系時遇到了困難,實體框架周圍包裹着一個存儲層。

從導航屬性(作為集合)中刪除和添加記錄不會導致數據庫發生任何更改(在數據庫日志攔截器中進行監視):

Resource newResource = resourceForAppointment.FirstOrDefault(x => x.ResourceId == schedulerEvent.ResourceId);
existingAppointment.Resources.Add(newResource);

Resource oldResource = resourceForAppointment.FirstOrDefault(x => x.ResourceId == schedulerEvent.PreviousResourceId);
existingAppointment.Resources.Remove(oldResource);

await this.Repository.UpdateAsync(existingAppointment);

讀取數據的效果很好,所以我懷疑它與配置有關:

[Table("Appointment")]
public partial class Appointment
{
    public Appointment()
    {        
        Resources = new HashSet<Resource>();
    }
    ...

    public virtual ICollection<Resource> Resources { get; set; }
}

這是我在存儲庫的異步方法中得到的:

 public virtual async Task<TEntity> UpdateAsync(TEntity entity)
 {
      this.Context.Set<TEntity>().Attach(entity);
      this.Context.Entry(entity).State = EntityState.Modified;
      await this.SaveChangesAsync();

      return entity;        
 }

更新簡單屬性和1對1導航屬性不是問題,這只是失敗的1對多對多關系。

就目前而言,作為一種解決方法,我正在使用以下代碼,我絕對需要擺脫這段不良的代碼:

   await this.ResourcesRepository.ExecuteSqlAsync($"DELETE FROM AppointmentResource WHERE AppointmentId = {existingAppointment.AppointmentID} AND ResourceID = {schedulerEvent.PreviousResourceId}");
   await this.ResourcesRepository.ExecuteSqlAsync($"INSERT INTO AppointmentResource VALUES({existingAppointment.AppointmentID},{schedulerEvent.ResourceId}) ");

這里的其他值得注意的評論包括我將Unity MVC用作存儲庫的引導程序,從而使用了PerRequestLifeTimeManager。 然后將此DbContext注入到工作單元類中,該工作單元類使用預定義的DbContext創建存儲庫。 因此,在請求的生存期內,僅存在1個活動的DbContext。

有誰知道如何解決這個問題?

更新:

當我說插入或更新不起作用時,我並不完全准確。 創建新的約會時,我可以向Resources集合中添加一條新記錄,如以下代碼摘錄所示:

// Map scheduler event to appointment
 Appointment newAppointment = Mapper.Map<Appointment>(schedulerEvent);

// Lookup resource by ID and add to new appointment      
Resource resourceForAppointment = await this.ResourcesRepository.FindOneAsync(x => x.ResourceId == schedulerEvent.ResourceId);
newAppointment.Resources.Add(resourceForAppointment);

 // Save to database
 Appointment freshAppointment = await this.Repository.CreateAsync(newAppointment);


public virtual async Task<TEntity> CreateAsync(TEntity entity)
{
   this.Context.Entry(entity).State = EntityState.Added;
   TEntity createdItem = Context.Set<TEntity>().Add(entity);
   await this.SaveChangesAsync();

   return createdItem;
}

由此我可以得出結論,存儲庫模式不一定會阻止一對多或多對多關系,但是我缺少其他東西。 希望這更有意義。

我為此提供了一個簡單的解決方案:我創建了一個新類,該類結合了多對多關系的ID。 與一些流利的api工作一起完成了工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM