尝试删除相关记录时,我做错了。我有一个客户模型和一个客户组模型。一个客户可以属于多个客户组。
我希望能够从客户组中添加和删除客户。添加是容易的部分,当我尝试从客户组中删除客户时,整个记录将从客户组表中删除
为了使事情易于理解,这是我的代码。
[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表中删除相关记录?
任何建议将不胜感激
删除CustomerGroup记录的原因是您将它们从上下文中删除,该上下文已翻译为完全从数据库中删除了它们。要仅删除与所选客户相关的CustomerGroup实例之间的关系,您必须将一个空白列表分配给SelectedGroups属性:
contextCustomer.SelectedGroups = new List<CustomerGroups>();
context.SaveChanges();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句