2012-02-21 86 views
0

我想先保存EF 4.1代碼中的級聯。EF 4.1級聯保存未保存

[Table("User")] 
public class User 
    { 
    [Key] 
    public Int64 UserId { get; set; } 
    public virtual UserRole UserRole { get; set; } 

} 

[Table("UserRole")] 
public class UserRole 
{ 
    [Key,Column(Order = 0)] 
    public int RoleID { get; set; } 
    [Key,Column(Order = 1)] 
    public Int64 UserId { get; set; } 


} 

當我試圖通過在其中填充userrole來保存用戶。它給錯誤。

INSERT語句與FOREIGN KEY約束條件 「FK_User_UserRole」衝突。衝突發生在數據庫「x」中,表 「dbo.User」列'UserId'。該語句已終止。

using (Database database = new Database()) 
{     
     database.User.Add(user); 
     database.SaveChanges(); //it is giving error here. 
} 

任何想法?

回答

1

您需要配置共享主鍵映射。否則,EF無法正確地對插入語句進行排序。在您的情況下,必須先插入User記錄,然後插入UserRole,並生成主密鑰User

[Table("User")] 
public class User 
    { 
    [Key] 
    public Int64 UserId { get; set; } 

    public virtual UserRole UserRole { get; set; } 
} 

[Table("UserRole")] 
public class UserRole 
{ 
    [Key,Column(Order = 0)] 
    public int RoleID { get; set; } 

    [Key,Column(Order = 1)] 
    public Int64 UserId { get; set; } 

    public virtual User User { get; set; } 
} 

在你OnModelCreating方法

modelBuilder.Entity<UserRole>().HasRequired(r => r.User) 
    .WithOptional(u => u.UserRole); 

然後

var user = new User { UserRole = new UserRole() }; 

using (Database database = new Database()) 
{     
     database.User.Add(user); 
     database.SaveChanges(); 
} 
0

我試圖重現錯誤如下,但是它成功

using (var db = new MyContext()) 
    { 
     var user = new User { UserRole = new UserRole { RoleID = 1, UserId = 1 } }; 
     db.Users.Add(user); 
     db.SaveChanges(); 
    } 

你能否詳細說明你的代碼更詳細地得到同樣的錯誤?