如何删除Entity Framework Core中的多对多关系?

时间:2017-04-18 20:24:20

标签: many-to-many asp.net-core-mvc entity-framework-core

我有两个实体框架实体。 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。但是我得到了这个错误:

&#34;实体类型之间的关联&#39;案例&#39;和&#39; EmployeeCase&#39;已被切断,但此关系的外键不能设置为null。 如果应删除依赖实体,则设置关系以使用级联删除。&#34;

此处我不需要删除案例或员工。我只需要删除连接记录。 进入该记录的唯一方法是从案例或员工进入关系。

如果我将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。如果不遵循这些步骤中的任何一个,则不会构建多对多模型。

我需要做的就是能够删除此记录。我不需要删除员工或案例。

以下是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; }

}

如何删除此多对多关系记录?

3 个答案:

答案 0 :(得分:6)

我遇到了同样的需求,并在此发现了这篇文章。由于真正的解决方案(使用EF)还没有发布,我决定添加这个答案:

另见Updating many to many relationships in 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属性的中间类(表)的列表。

答案 1 :(得分:0)

我最后只使用了原始的sql:

    [HttpPost]
    public async Task<Employee> AddCaseEmployee([FromBody]EmployeeCase employeeCase)
    {
        string queryString = "INSERT INTO EmployeeCase VALUES (@EmployeeId, @CaseId)";
        SqlParameter[] sqlParams = new SqlParameter[]
        {
            new SqlParameter { ParameterName = "EmployeeId", Value = employeeCase.EmployeeId },
            new SqlParameter { ParameterName = "CaseId", Value = employeeCase.CaseId },
        };
        _context.Database.ExecuteSqlCommand(queryString, sqlParams);
        Employee employee = await _employeeGenericService.GetSingleIncludingAsync(employeeCase.EmployeeId);

        return employee;
    }

    [Authorize(Roles = "LERSpecialist, Admin")]
    [HttpDelete]
    public async Task<IActionResult> DeleteCaseEmployee(long employeeId, long caseId)
    {

        string queryString = "DELETE FROM EmployeeCase WHERE EmployeeId = @EmployeeId AND CaseId = @CaseId";
        SqlParameter[] sqlParams = new SqlParameter[]
        {
            new SqlParameter { ParameterName = "EmployeeId", Value = employeeId },
            new SqlParameter { ParameterName = "CaseId", Value = caseId },
        };
        _context.Database.ExecuteSqlCommand(queryString, sqlParams);

        return NoContent();
    }

我开始倾向于使用Entity Framework进行查询。 (在查询时让我.Net Serialize到JSON。) 但是使用RAW Sql或存储过程的所有其他CRUD(数据操作)。

答案 2 :(得分:0)

我遇到了几乎相同的问题(具有几乎相同的基础类;具有中间AB类的A <-> B多对多);删除“ A”记录时的解决方法:

var targetToDelete = await context.A.Include(a =>a.B)                
            .Where(a => a.Id == idToDelte)
            .FirstOrDefaultAsync();
context.A.Remove(targetToDelete );

因此,当包含B时,EntityFrameworkCore似乎可以自动解决问题。 (要使用“包含”,请不要忘记添加“使用Microsoft.EntityFrameworkCore;”)