MVC删除具有多个必需外键约束的记录。

3

在MVC中,从联接载荷表中删除数据一点也不有趣。类似的问题都是关于单个外键的,而我的情况是独特的,我认为这应该成为一个独立的问题(如果不是,请指引我参考资料)

我有这个模型(它充当我的带载荷的联接表 - 它作为ApplicationUser和Car之间的联接表,它们都是数据模型)

public class UserHasCar
{
    // Foreign keys
    [Key, Column(Order = 0)]
    public string ApplicationUserId { get; set; }

    [Key, Column(Order = 1)]
    public int CarId { get; set; }

    // Navigation properties
    [Required]
    public virtual ApplicationUser ApplicationUser { get; set; }

    [Required]
    public virtual Car Car { get; set; }

    // Additional fields
    public int YearsDriven { get; set; }

}

public class Car
{
    public int ID { get; set; }

    public virtual ICollection<UserHasCar> UserHasCars { get; set; }
}

public class ApplicationUser : IdentityUser
{
    public virtual ICollection<UserHasCar> UserHasCars { get; set; } 
}

当我试图从数据库中删除一条记录(即删除UserHasCar实体)时,出现了问题。由于UserHasCar有两个外键,运行此代码后,我会收到以下错误:

List<UserHasCar> list = (from t in context.UserHasCars where t.ApplicationUserId == userId select t).ToList();

        foreach (UserHasCar car in list)
        {
            context.UserHasCar.Remove(car); // BOOM!
        }

这个错误提示是:违反了引用完整性约束条件:当从属对象的状态为Unchanged时,作为引用完整性约束条件的主键属性不能被更改,除非它正在被设置为关联的主体对象。主体对象必须被跟踪并且没有被标记为删除。

我的表定义如下:

CREATE TABLE [dbo].[UserHasCars] (
[ApplicationUserId] NVARCHAR (128) NOT NULL,
[CarId]           INT            NOT NULL,
[YearsDriven]  INT            NOT NULL,
CONSTRAINT [PK_dbo.UserHasCars] PRIMARY KEY CLUSTERED ([ApplicationUserId] ASC, [CarId] ASC),
CONSTRAINT [FK_dbo.UserHasCars_dbo.AspNetUsers_ApplicationUserId] FOREIGN KEY ([ApplicationUserId]) REFERENCES [dbo].[AspNetUsers] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.UserHasCars_dbo.Cars_CarId] FOREIGN KEY ([CarId]) REFERENCES [dbo].[Cars] ([ID]) ON DELETE CASCADE
);

我必须对我的两个外键执行像EntityState.Deleted/Modified这样的简单操作吗?我知道它在抱怨我的聚簇主键以及如果我不删除对我的外键的引用就无法删除它......我确定我在这里漏掉了一些小东西。
编辑 当我仔细查看时,这行代码 List<UserHasCar> list = (from t in context.UserHasCars where t.ApplicationUserId == userId select t).ToList(); 没有从我的数据库表中正确地获取ApplicationUser或Car,所有值都为null。我可以看到查询没有正确地获取ApplicationUser或Car,但为什么?

还有其他表使用此表UserHasCars作为[ApplicationUserId]列的外键约束,并带有ON DELETE CASCADE吗? - Stoleg
@Stoleg 不是,但我偶然发现了解决这个问题的方法。我会提到它。 - reZach
5个回答

1
外键数据正在发送到模型中吗?
如果您正在使用Entity Framework测试: Modelo.Remove(data) Modelo.SaveChanges();

1

1
你可以尝试将它从主实体中删除吗?例如:
var user = dbContext.Users.Where(u => u.userId == userId);

foreach(var car in user.Cars) {
    user.Cars.Remove(car);
}

0
问题在于汽车和用户 ID 被设置为默认值,并不代表表中的实际行。我已经在这个页面上写了如何解决它的方法(接近页面底部):

http://programmerscheatbook.blogspot.com/2014/08/mvc-making-join-table-with-payload.html

ApplicationDbContext db = new ApplicationDbContext();

string userId = [USER ID];
int carId = [CAR ID];

List <UserHasCar> list = (from rec in db.UserHasCars
                      join car in db.Cars on rec.CarId equals car.Id
                      where rec.ApplicationUserId == userId && rec.CarId == carId
                      select rec).ToList();

foreach (UserHasCar car in list)
{
    db.UserHasCars.Remove(car);
}

db.SaveChanges();

-1
public ActionResult DeleteConfirmed(long id)
{
    EmployeeContacts employeecontect = db.EmployeeContacts.Find(id);
    if(employeecontect!=null)
    { 
        db.EmployeeContacts.Remove(employeecontect);
        db.SaveChanges();
    }
    Employee employee = db.Employee.Find(id);
    db.Employee.Remove(employee);
    db.SaveChanges();

    return RedirectToAction("Index");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接