2016-07-14 7 views
0

は私のサンプルコードで、私はサンプルにデータを挿入しようと私はテーブルを作成し、ここで

class Sample 
{ 
public int Id{ get;set; } 
public int AssociatedSiteId { get; set; } 
     [ForeignKey("AssociatedSiteId")] 
     public virtual SiteA Site { get; set; } 
     [ForeignKey("AssociatedSiteId")] 
     public virtual SiteB SiteB { get; set; } 
} 

I m Inserting the data as 
using (var dbcontext = new sampleEntities) 
{ 
var sample = new Sample(); 
sample.Id=1; 
sample.AssociateId = siteInfo.SiteId; // This Id from SiteA Table 
dbcontext.Sample.Add(sample); 
dbcontext.SaveChanges(); 
} 

あるEFコードファーストアプローチに二つの他のテーブルへの外部キーとして列を作った、私のようにエラーを得メートル:

INSERTステートメントがFOREIGN KEY制約と競合しました。

私はEFを初めてお使いになれますか?

+0

あなたが挿入コードを投稿することができますか? – bwyn

+0

var sample = new Sample(); Sample.UserName = userName; sample.IsSuccess = true; sample.IsActive = true; sample.NoofAttempts = 1; sample.LoginTime = DateTime.UtcNow; sample.SessionTimeStamp = DateTime.UtcNow; sample.IsConsultSite = false; sample.AssociatedSiteId = siteInfo.SiteId; dbContext.Sample.Add(sample); dbContext.SaveChanges(); –

+0

あなたの質問にコードを編集してください。コメントとしては読めません。 – jmoerdyk

答えて

0

私はあなたには、いくつかの指導を必要とすると仮定しています:)

私は質問があります。なぜサイトとSiteBのは、同じ外部キー変数を使用しているの?それらは異なるエンティティではありませんか?あなたは

Sample.SiteA => MySiteA 
Sample.SiteB => MySiteB 

they cannot use the same foreignh key. Even if they are the same type, that key is used to locate the foreign entity and you would be overwriting one with the another... Check your code with mine. 

を持っている場合(サイトAとのSiteB)

は、以下のことを試してください:あなたのコードで

class Sample 
{ 
    public int Id{ get;set; } 

    public int AssociatedSiteAId { get; set; } // Optional but sometimes useful if you don't use [ForegnKey("...")] 

    [ForeignKey("AssociatedSiteAId")] 
    public virtual SiteA Site { get; set; } 


    public int AssociatedSiteBId { get; set; } // Optional but sometimes useful if you don't use [ForegnKey("...")] 

    [ForeignKey("AssociatedSiteBId")] 
    public virtual SiteB SiteB { get; set; } 
} 

using (db = new DbContext()) 
{ 
    var site_a = db.SitesA.Find(123); // 1 should be the key of site a 
    var site_b = db.SitesB.Find(456); // 2 should be the key of site b 

    Sample sample = new Sample() 
    { 
    SiteA = site_a, 
    SiteB = site_b 
    }; 

    db.Samples.Add(sample); 
    db.SaveChanges(); 
} 
+0

こんにちは、ホルヘ、返信いただきありがとうございます。私のシナリオでは、SiteAとSiteBの両方のsiteIdsを取得して参照用に保存する必要があります –

+0

私が投稿した例はまさにそれです。問題は、エンティティ間で1つの外部キーを共有していることです。 SiteAにキー123があり、SiteBにキー456があるとします。この値はAssociatedSiteIdに格納されますか? 123または456? –

+0

明確にするために:AssociatedSiteIdはintであり、intを1つしか格納できません。それはあなたの関係の1つのキー(siteId)を保存します。他の鍵はどこに行きますか? –

関連する問題