如何刪除Entity Framework Core中的多對多關係?

asp.net-core-mvc entity-framework-core many-to-many

我有兩個實體框架實體。 1)員工2)案例

我在Entity Framework Core中建模了多對多的關係。

我可以像這樣添加一個關係:

    [HttpPost]
    public async Task<Employee> AddCaseEmployee([FromBody]EmployeeCase employeeCase)
    {
        Case lcase = await _caseGenericService.GetSingleIncludingAsync(employeeCase.CaseId);

        lcase.EmployeeCases = new List<EmployeeCase>();
        lcase.EmployeeCases.Add(new EmployeeCase
            {
                CaseId = employeeCase.CaseId,
                EmployeeId = employeeCase.EmployeeId
            }
        );

        await _caseGenericService.UpdateAsync(lcase);

        Employee employee = await _employeeGenericService.GetSingleIncludingAsync(employeeCase.EmployeeId);
        return employee;
    }

現在我試圖刪除這樣的一個關係:

    [HttpDelete]
    public async Task<Employee> DeleteCaseEmployee(long employeeId, long caseId)
    {
        Case lcase = await _caseGenericService.GetSingleIncludingAsync(caseId,
            a => a.EmployeeCases);

        //lcase.EmployeeCases.Remove(new EmployeeCase
        //{
        //    CaseId = caseId,
        //    EmployeeId = employeeId
        //}
        //);
        EmployeeCase employeeCase = 
            lcase.EmployeeCases.FirstOrDefault(ec => ec.EmployeeId == employeeId && ec.CaseId == caseId);
        lcase.EmployeeCases.Remove(employeeCase);

        try
        {
            await _caseGenericService.UpdateAsync(lcase);
        }
        catch(Exception ex)
        {

        }

        Employee employee = await _employeeGenericService.GetSingleIncludingAsync(employeeId);
        return employee;
    }

你可以看到我的第一次嘗試被註釋掉了。所以我嘗試了第二種方法,只是取回我要刪除的記錄的引用,將其從集合中刪除,然後調用update。但我得到這個錯誤:

“實體類型'Case'和'EmployeeCase'之間的關聯已被切斷,但此關係的外鍵不能設置為null。如果應刪除依賴實體,則設置關係以使用級聯刪除。”

在這裡,我不需要刪除案例或員工。我只需要刪除連接記錄。進入該記錄的唯一方法是從案例或員工進入關係。

如果我將EmployeeCase對象設為Dbset,則不會構建模型。

這是我建立OnModelBuilding的關係:

    modelBuilder.Entity<EmployeeCase>()
            .HasKey(ec => new { ec.EmployeeId, ec.CaseId });

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Employee)
            .WithMany(e => e.EmployeeCases)
            .HasForeignKey(ec => ec.EmployeeId);

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Case)
            .WithMany(c => c.EmployeeCases)
            .HasForeignKey(ec => ec.CaseId);

        // Get rid of Cascading Delete Circular references error.
        var type = modelBuilder.Model.GetEntityTypes().Single(t => t.Name == "Hrsa.Core.Generic.Model.Lerd.EmployeeCase");
        foreach (var relationship in type.GetForeignKeys())
        {
            relationship.DeleteBehavior = DeleteBehavior.Restrict;
        }

我不得不關閉連接對象,EmployeeCase的Deletes,它不能是DbSet。如果不遵循這些步驟中的任何一個,則不會構建多對多模型。

我需要做的就是能夠刪除此記錄。我不需要刪除Employee或Case。

這是POCO。

public class Employee : BaseEntity
{
    [BindNever]
    public string Email { get; set; }
    [BindNever]
    public long OrganizationId { get; set; }
    [BindNever]
    public string Supervisor { get; set; }
    [BindNever]
    public string SupervisorEmail { get; set; }
    [BindNever]
    public string FirstName { get; set; }
    [BindNever]
    public string LastName { get; set; }
    public string Notes { get; set; }
    [BindNever]
    public  long BargainingUnitId { get; set; }
    [BindNever]
    public long PayPlanId { get; set; }
    [BindNever]
    public long GradeRankId { get; set; }
    [BindNever]
    public long PositionTitleId { get; set; }
    [BindNever]
    public long SeriesId { get; set; }
    public bool IsUnionEmployee { get; set; }
    public virtual Organization Organization { get; set; }
    public virtual BargainingUnit BargainingUnit { get; set; }
    public virtual PayPlan PayPlan { get; set; }
    public virtual GradeRank GradeRank { get; set; }
    public virtual PositionTitle PositionTitle { get; set; }
    public virtual  Series Series { get; set; }
    public virtual ICollection<UnionHours> UnionHours { get; set; }
    [NotMapped]
    public string UnionEmployeeYesNo => (IsUnionEmployee) ? "Yes" : "No";

    public virtual ICollection<EmployeeCase> EmployeeCases { get; set; }

}

public class Case : BaseEntity
{
    #region Common Case Properties
    public long InitialContactId { get; set; }
    public virtual Employee InitialContact { get; set; }
    [DataType(DataType.Date)]
    public DateTime? InitialConsultDate { get; set; }
    public string LerSpecialistId { get; set; }
    public virtual AppUser LerSpecialist { get; set; }
    public string Notes { get; set; }

    public bool IsDeleted { get; set; }
    public CaseType CaseType { get; set; }
    #endregion

    #region EmployeeCase Properties
    //public long PrimaryEmployeeId { get; set; }
    //public virtual Employee PrimaryEmployee {get;set;}
    public virtual ICollection<EmployeeCase> EmployeeCases { get; set; }
    #endregion

    #region NonEmployeeCase Properties
    //public long PrimaryNonEmployeeId { get; set; }
    //public virtual Employee PrimaryEmployee {get;set;}
    public virtual ICollection<NonEmployeeCase> NonEmployeeCases { get; set; }
    #endregion
}

和連接表(再次,不是DbSet,但是一切都在添加關係。現在只是無法刪除。)

public class EmployeeCase
{
    [ForeignKey("Id")]
    public long EmployeeId { get; set; }
    public Employee Employee { get; set; }
    [ForeignKey("Id")]
    public long CaseId { get; set; }
    public Case Case { get; set; }

}

如何刪除這對多對多關係記錄?

熱門答案

我遇到了同樣的需求,並在這裡找到了這篇文章。由於真正的解決方案(使用EF)還沒有發布,我決定添加這個答案:

另請參閱在Entity Framework Core中更新多對多關係 ;這是用於更新,但相同的原則適用於刪除。

這是我的代碼(我的場景是用戶N“N組):

var groupToUpdate = _userGroupsContext.Groups.Include(g => g.UserGroups).Single(u => u.Id == userVm.groupsIds[0]);
var userToUpdate = _userGroupsContext.Users.Single(u => u.Id == userVm.user.Id);

groupToUpdate.UserGroups.Remove(groupToUpdate.UserGroups.Where(ugu => ugu.UserId == userToUpdate.Id).FirstOrDefault());
_userGroupsContext.SaveChanges();

UserGroups字段是包含groupgroupIduseruserId屬性的中間類(表)的列表。



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow