2015-06-16 38 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)你假设临时本组织存在。

相关问题