开发者

EF Code First - Seeding data that needs foreign key reference

开发者 https://www.devze.com 2023-03-04 04:11 出处:网络
I have 2 entities - Roles and Administrators. Roles has two values - Search Admin and Super Admin. I have created these using EF Code First model. Now I am trying to seed values to the database and I

I have 2 entities - Roles and Administrators. Roles has two values - Search Admin and Super Admin. I have created these using EF Code First model. Now I am trying to seed values to the database and I add the roles first:

开发者_高级运维
    private static void SeedRoles(PayByPhoneDbContext context)
    {
        var roles = new List<Role> {new Role {Name = "Search Administrator"}, new Role {Name = "Super Administrator"}};
        roles.ForEach(role => context.Roles.Add(role));
    }

Now I want to use one of the roles created above to be used while adding administrators:

    private void SeedAdministrators(PayByPhoneDbContext context)
    {
        var administrators = new List<Administrator>{new Administrator {Email = "a@a.com", Name = "Achinth Gurkhi", Password = "hello", Active = true, Role = ? }}
    }

How do I set Role here? Should I say Role = new Role { Name = "Super Administrator" } or search for Role inserted by SeedRoles method? Also, how do I search for an existing role using the context?


If both methods are called before you execute SaveChanges on your context you must use the same role instance you created in SeedRoles otherwise you will create another Role with the same name. You must either pass created role / roles to SeedAdministrators (which is correct approach) or you can try to query context.Roles.Local.Where(r => r.Name = "...") and search for the role.

0

精彩评论

暂无评论...
验证码 换一张
取 消