2014-10-11 9 views
6

जब मैं निम्न माइग्रेशन चलाने के लिए, मैं निम्नलिखित त्रुटि हो रही है के साथ विरोध हुआ:परिवर्तन तालिका कथन विदेशी कुंजी बाधा

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

मैं एक मौजूदा डेटाबेस और मॉडल पुनर्रचना एक नेविगेशन संपत्ति शामिल करने के लिए की है।

मूल मॉडल:

public class Student 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public string Country { get; set; } 
} 

नए मॉडल:

public class Student 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public int CountryID { get; set; } 
    public virtual Country Country { get; set; } 
} 

public class Country 
{ 
    public int ID { get; set; }    
    public string Country { get; set; } 
} 

Add-Migration नेविगेशन संपत्ति:

public override void Up() 
{ 
      CreateTable(
       "dbo.Countries", 
       c => new 
        { 
         ID = c.Int(nullable: false, identity: true), 
         CountryName = c.String(), 
        }) 
       .PrimaryKey(t => t.ID); 

      AddColumn("dbo.Students", "CountryID", c => c.Int(nullable: false)); 
      CreateIndex("dbo.Students", "CountryID"); 
      AddForeignKey("dbo.Students", "CountryID", "dbo.Countries", "ID", cascadeDelete: true); 
      DropColumn("dbo.Students", "Country"); 
} 

मूल मॉडल और उसके बाद नए मॉडल देखेंUpdate-Database त्रुटि:

System.Data.SqlClient.SqlException (0x80131904): The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Students_dbo.Countries_CountryID". The conflict occurred in database "aspnet-navprop-20141009041805", table "dbo.Countries", column 'ID'.

+0

यह प्रश्न क्यों मतदान किया गया था? मैंने सोचा कि सवाल अच्छी तरह से प्रलेखित था। –

उत्तर

3

मुझे एक ही समस्या मिली, मेरी तालिका में डेटा था इसलिए मैंने विदेशी कुंजी कॉलम को निरर्थक में बदल दिया।

AddColumn("dbo.Students", "CountryID", c => c.Int(nullable: true)); 

आप अपने कोड की तरह फिर अपने छात्र इकाई के खिलाफ आप प्रकार से संलग्न एक प्रश्न चिह्न का उपयोग कर नल के रूप में अपने countryID संपत्ति चिह्नित कर सकते हैं बदलना चाहिए चला अद्यतन-डाटाबेस -verbose

public override void Up() 
{ 
      CreateTable(
       "dbo.Countries", 
       c => new 
        { 
         ID = c.Int(nullable: false, identity: true), 
         CountryName = c.String(), 
        }) 
       .PrimaryKey(t => t.ID); 

      AddColumn("dbo.Students", "CountryID", c => c.Int(nullable: true)); 
      CreateIndex("dbo.Students", "CountryID"); 
      AddForeignKey("dbo.Students", "CountryID", "dbo.Countries", "ID", cascadeDelete: true); 
      DropColumn("dbo.Students", "Country"); 
} 
3

मैं इस एक ही मुद्दा था और विदेशी कुंजी रिकॉर्ड के साथ तालिका छोटा कर दिया है और यह सफल रहा।

2

यदि तालिका में कोई डेटा है (छात्र तालिका) उन्हें हटाएं और फिर पुन: प्रयास करें।

0

, यानी

public class Student 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public int? CountryID { get; set; } 
    public virtual Country Country { get; set; } 
} 
संबंधित मुद्दे