ED代码首先一对多关系问题 - ASP身份

时间:2015-06-16 12:58:19

标签: entity-framework ef-code-first one-to-many

我正在为ASP身份配置数据库,我遇到了麻烦。

我希望在两个表格之间创建一个One to Many关系,ApplicationUser& OrganisationUnit

OrganisationUnit可以有多个ApplicationUsersApplicationUser只属于一个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 = "derek@rdsadfasdf.com",
                EmailConfirmed = true,
                Forename = "Derek",
                Surname = "Rivers",
                DateCreated = DateTime.Now.AddYears(-3),
                OrganisationUnitId = ou.Id
            };

            userManager.Create(user, "MySuperP@ssword!");
        }
    }

1 个答案:

答案 0 :(得分:1)

你应该尝试:

        var user = new ApplicationUser()
        {
            UserName = "SuperPowerUser",
            Email = "derek@rdsadfasdf.com",
            EmailConfirmed = true,
            Forename = "Derek",
            Surname = "Rivers",
            DateCreated = DateTime.Now.AddYears(-3),
            OrganisationUnit = ou
        };

使用您的语法(仅提供FK),您假设组织存在。