2015-06-16 37 views
0

我正在爲ASP身份配置一個數據庫,並且我遇到了麻煩。ED代碼首先一對多的關係問題 - ASP身份

我期待創建一個One to Many兩個表之間的關係,它們是ApplicationUser & OrganisationUnit

的OrganisationUnit可以有多個ApplicationUsers,與ApplicationUser只屬於一個OrganisationUnit

當我添加了遷移,並且在執行過程中更新我得到一個錯誤的數據庫: -

System.Data。 SqlClient.SqlException:INSERT語句衝突 與FOREIGN KEY約束 「FK_dbo.AspNetUsers_dbo.OrganisationUnits_OrganisationUnitRefId」。 衝突發生在數據庫「DefaultConnection」,表 「dbo.OrganisationUnits」列'OrganisationUnitId'中。

這裏是我試圖創建表: -

public class ApplicationUser : IdentityUser 
    { 
     [Required] 
     [MaxLength(100)] 
     public string Forename { get; set; } 

     [Required] 
     [MaxLength(100)] 
     public string Surname { get; set; } 

     [Required] 
     public DateTime DateCreated { get; set; } 

     public Guid OrganisationUnitId { get; set; } 

     [ForeignKey("OrganisationUnitId")] 
     public virtual OrganisationUnit OrganisationUnit { get; set; } 

    } 



    public class OrganisationUnit 
     { 

      public OrganisationUnit() 
      { 
       ApplicationUsers = new List<ApplicationUser>(); 
      } 


      public Guid Id { get; set; } 

      [Required] 
      [MaxLength(100)] 
      public string Name { get; set; } 

      [Required] 
      [MaxLength(100)] 
      public string Telephone { get; set; } 
      public virtual ICollection<ApplicationUser> ApplicationUsers { get; set; } 
     } 

在我的種子法的Configuration.cs有以下代碼: -

protected override void Seed(ApplicationDbContext context) 
     { 
      // This method will be called after migrating to the latest version. 

      var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); 

      var ou = new OrganisationUnit() 
      { 
       Id = Guid.NewGuid(), 
       Name = "Group1", 
       Telephone = "1234567890", 
      }; 

      var user = new ApplicationUser() 
      { 
       UserName = "SuperPowerUser", 
       Email = "[email protected]", 
       EmailConfirmed = true, 
       Forename = "Derek", 
       Surname = "Rivers", 
       DateCreated = DateTime.Now.AddYears(-3), 
       OrganisationUnitId = ou.Id 
      }; 

      userManager.Create(user, "[email protected]!"); 
     } 
    } 

回答

1

你應該嘗試:

 var user = new ApplicationUser() 
     { 
      UserName = "SuperPowerUser", 
      Email = "[email protected]", 
      EmailConfirmed = true, 
      Forename = "Derek", 
      Surname = "Rivers", 
      DateCreated = DateTime.Now.AddYears(-3), 
      OrganisationUnit = ou 
     }; 

隨着你的語法(只限於FK)你假設臨時本組織存在。

相關問題