Seed entity with owned property

后端 未结 5 1998
深忆病人
深忆病人 2021-02-12 13:41

I am trying to seed an user entity in my database. The User entity has an owend property EmailPermissions.

When I run the command

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-12 14:42

    Thank Ivan Stoev's answer. i add some more code to easy to imagine. this is code of seed data function base on example.

    • First adding data of User.
    • After that add data of owned object.
    • Data of owned object have to be anonymous because PK will request. This PK will not appear in database. Name should be entity name + Id

    Example: Entity XXX => PK will be XXXId

    private void SeedUser(ModelBuilder builder)
    {
        builder.Entity(b =>
        {
            b.HasData(new User
            {
                Id = "37846734-172e-4149-8cec-6f43d1eb3f60",
                Email = "foo@foo.foo",
                UserName = "foo@foo.foo",
                // more properties of User
            });
            b.OwnsOne(e => e.EmailPermissions).HasData(new 
            {
                    UserId = "37846734-172e-4149-8cec-6f43d1eb3f60",
                    Newsletter = true,
                    PromotionalOffers = true,
                    PrestationReminders = true,
                    PrestationOffers = true
            });
        });
    }
    

提交回复
热议问题