使用外键删除对象的实体框架错误

问题描述 投票:0回答:1

我需要删除已经创建了事件的联系人,数据的保存结构如下

事件表

enter image description here

联系人表

enter image description here

我有一个单独的表,称为EventContacts,用于管理事件和联系人之间的关系

enter image description here

活动类

public class Events
    {

        [Key]
        public string id { get; set; }
        public string title{ get; set; }
        public string desc{ get; set; }
        public virtual List<Contact> contacts{ get; set; }
    }

联系人类别

public class Contact
    {
        public string ContactId { get; set; }  
        public string name{ get; set; }
        public string email{ get; set; }
    }

我使用此代码删除联系人

using (var db= new DatabaseModel())
{
     Contact contact = db.Contacts.Find(id);
     db.Contact.Remove(contact);
     db.SaveChanges();
}

要添加事件,我使用此方法

List<Contact> cons = new List<Contact>();
foreach (ComboItem cmb in cbItems)
{
   EventContact evntConts = new EventContact()
   {
      contId = cmb.contId,
      evntId = eventidevntId
      userId = userId,
    };

    cons.Add(evntConts);
}
UserEvent events = new UserEvent()
{
   eventid= this.evntid,
   title= txt_title.Text,
   description = txt_des.Text,
   contacts = cons
};



using (var db= new DatabaseModel())
{
   db.Evnts.Add(evnt);
   db.SaveChanges();
}

如果没有与该用户一起创建的事件,那么此代码可以正常工作,但是如果我将用户添加到事件中然后再删除该用户,则此代码将无法正常工作。我该如何解决?

c# database winforms linq
1个回答
0
投票

我还没有测试代码,但这应该可以让您在删除联系人本身之前从事件中删除联系人。

© www.soinside.com 2019 - 2024. All rights reserved.