简体   繁体   English

[已更新]使用 FK 的表中的 Can 种子数据

[英][UPDATED]Can's seed data in a table with FK

There two tables有两张桌子

User and Preference.用户和偏好。 User has FK Preference.用户有 FK 偏好。 Trying to add data to both tables using migration.尝试使用迁移将数据添加到两个表中。

        modelBuilder.Entity<User>().OwnsOne(p => p.Preference).HasData(
            new Preference
            {
                Id = Guid.Parse("A6293AB4-3A1B-4780-F207-0BC92650778B"),
                //other properties
            }
        );

        modelBuilder.Entity<User>().HasData(new User
        {
            Id = Guid.Parse("f90gh1b1-c121-4962-sa96-5c6fdb2af1ab"),
            //some other properties...
            
        });

Error I am getting when running add migration command.运行添加迁移命令时出现错误。

The seed entity for entity type 'Preference' cannot be added because no value was provided for the required property 'UserId'.

There is no PreferenceId in User.用户中没有 PreferenceId。 Only Preference object.只有 Preference 对象。 In cs files, User.cs has在 cs 文件中,User.cs 有

    public virtual Preference Preference { get; set; } = null!;

UPDATE I added public Guid PreferenceId{get;set;} to User.cs, changed the code like this :更新我将public Guid PreferenceId{get;set;}添加到 User.cs,更改代码如下:

modelBuilder.Entity<User>().HasData(new User
        {
            Id = Guid.Parse("f90gh1b1-c121-4962-sa96-5c6fdb2af1ab"),
            //some other properties...
            PreferenceId = Guid.Parse(someGuid)
        });

REMOVED OwnsOne part.删除了OwnsOne 部分。 Updated DB and the record was added.更新了数据库并添加了记录。 How do I know if this was added as FK or not?我怎么知道这是否被添加为 FK?

By adding the public virtual Preference Preference { get; set; } = null!;通过添加public virtual Preference Preference { get; set; } = null!; public virtual Preference Preference { get; set; } = null!; into your user class it creates the FK to preferences.进入您的用户类,它会为首选项创建 FK。

One way to do it would be to create a new user object and set the preferences variable to an object.一种方法是创建一个新的用户对象并将首选项变量设置为一个对象。 eg例如

modelBuilder.Entity<User>().HasData(new User
    {
        Id = Guid.Parse("f90gh1b1-c121-4962-sa96-5c6fdb2af1ab"),
        Preference = new Preference
        {
            Id = Guid.Parse("A6293AB4-3A1B-4780-F207-0BC92650778B"),
            //other properties
        }

        //some other properties...
        
    });

Hope I am understanding the question correctly希望我能正确理解这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM