2014-12-07 57 views
0

我已經創建了簡單的asp.net(MVC4)網頁與MySQL數據庫。在那裏我有兩個表格(人員和訂單),其中表格訂單具有FORIGN Key Persons_ID。我希望創建刪除功能,因此,當我從人員表中刪除人員時,它也會刪除該人員的訂單表中的所有訂單。級聯刪除MySQL和ASP.NET MVC4

爲了創建模型我已經使用ADO.NET,併爲每個表創建此兩種模式:使用System.ComponentModel.DataAnnotations

persons.cs ;

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 - 像上述兩個模型我容器:

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; } 

    } 
} 

現在對於級聯刪除我試試這個 - 所以當我刪除Person,它也會刪除此人的所有訂單,訂單表,但這似乎不工作

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); 
     } 
    } 
} 

回答

1

可能是你可以嘗試這樣的事情

modelBuilder.Entity<order>() 
    .HasRequired(a => a.person) 
    .WithMany(t => t.order) 
    .HasForeignKey(d => d.Persons_Id) 
    .WillCascadeOnDelete(true); 

或嘗試在這裏閱讀更多MSDN Cascade Delete。可能有些東西可以從那裏幫助

+0

tnx回覆,我會盡快嘗試。但我給你投票了。 – DaniKR 2014-12-12 07:01:54