我在尝试删除相关记录时出错了。 我有一个Customer模型和一个CustomerGroup模型。客户可以属于多个客户组。
我希望能够在客户群中添加和删除客户。添加是很容易的部分,当我尝试从客户组中删除客户时,整个记录将从客户组表中删除
为了使事情易于理解,这是我的代码。
[Table("CustomerGroups")]
public class CustomerGroupModel
{
[Key]
[DataMember]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CustomerGroupId { get; set; }
[DataMember]
public Guid BusinessId { get; set; }
public virtual Business Business { get; set; }
[DataMember]
[Display(Name = "Group Name")]
public string GroupName { get; set; }
[ScriptIgnore]
public virtual List<Customer> CustomersInGroup { get; set; }
}
我的客户模式
[Table("Customers")]
[DataContract]
public class Customer
{
[DataMember]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
[DataMember(IsRequired = true)]
[Required(ErrorMessage = "First Name is required")]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[DataMember(IsRequired = true)]
[Required(ErrorMessage = "Last Name is required")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[DataMember]
public string FullName
{
get { return string.Format("{0} {1}", FirstName, LastName); }
}
[DataMember]
[Display(Name = "Groups")]
//change this as ICollection failed with restsharp to bindICollection<CustomerGroupModel> SelectedGroups { get; set; }
public virtual List<CustomerGroupModel> SelectedGroups { get; set; }
}
我的FluentApi
modelBuilder.Entity<Customer>()
.HasMany(x => x.SelectedGroups)
.WithMany(x => x.CustomersInGroup).Map(
m =>
{
m.MapLeftKey("CustomerId");
m.MapRightKey("CustomerGroupId");
m.ToTable("CustomersInGroups");
});
如您所见,我生成了一个名为CustomersInGroups的表。
当我尝试更新客户群时,我想删除所有现有记录,然后重新插入新选择的记录(除非有更好的方法)
using (var context = new MyContext())
{
var contextCustomer = context.Customers
.Include("SelectedGroups")
.SingleOrDefault(a => a.Id==customer.Customer.Id);
contextCustomer.SelectedGroups.ToList()
.ForEach(r => context.CustomerGroups.Remove(r));
context.SaveChanges();
}
执行此操作时,将删除表CustomerGroups中的所有记录。我如何只删除customersingroups表中的相关记录?
任何建议都会非常感激
答案 0 :(得分:1)
删除CustomerGroup记录的原因是您将其从已转换为从数据库中完全删除的上下文中删除。要仅删除与所选客户相关的CustomerGroup实例之间的关系,您必须为SelectedGroups属性分配一个空列表:
contextCustomer.SelectedGroups = new List<CustomerGroups>();
context.SaveChanges();