【发布时间】:2014-12-07 15:15:49
【问题描述】:
我用 mysql 数据库创建了简单的 asp.net (MVC4) 网页。我有两个表(人员和订单),其中表订单具有 FORIGN 键 Persons_ID。我想创建删除功能,所以当我从persons表中删除一个人时,它也会从这个人的order表中删除所有订单。
为了创建模型,我使用了 ADO.NET,它为每个表创建了这两个模型:
persons.cs 使用 System.ComponentModel.DataAnnotations;
namespace MvcMySQLTest1.Models
{
using System;
using System.Collections.Generic;
public partial class person
{
public person()
{
this.orders = new HashSet<order>();
}
public int ID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Adress { get; set; }
public string City { get; set; }
public virtual ICollection<order> orders { get; set; }
}
}
orders.cs
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MvcMySQLTest1.Models
{
using System;
using System.Collections.Generic;
public partial class order
{
public int O_Id { get; set; }
public int OrderNo { get; set; }
public Nullable<int> Persons_Id { get; set; }
public virtual person person { get; set; }
}
}
我还创建了 MainModel - 就像上面两个模型的 I 容器:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
namespace MvcMySQLTest1.Models
{
public class MainModel
{
public person Persons { get; set; }
public order Orders { get; set; }
}
}
现在对于级联删除我已经尝试过 - 所以当我删除人员时,它也会删除订单表中此人员的所有订单,但这似乎不起作用:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
namespace MvcMySQLTest1.Models
{
public class MainModel : DbContext //added
{
public person Persons { get; set; }
public order Orders { get; set; }
//added
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<orders>()
.HasOptional(a => a.persons)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
}
}
【问题讨论】:
标签: mysql asp.net-mvc cascade cascading-deletes