迁移在表中添加了一个额外的列,而没有模型中的属性

时间:2018-03-16 07:00:39

标签: c# asp.net-mvc database-migration asp.net-core-2.0

我正在使用.NET Core 2 MVC,我有以下模型:

BooksCategories模型:

 public class BooksCategories
{
    [Key]
    public int BookCategoryId { get; set; }

    [Required]
    public string Name { get; set; }

    public bool isSelected { get; set; }
}

FirstInput模型:

public class FirstInput
{
    //[Key]
    public int FirstInputId { get; set; }

    public string UserId { get; set; }

    [ForeignKey("UserId")]
    public virtual ApplicationUser User { get; set; }

    public bool Books { get; set; }

    public string SelectedBookCategories { get; set; }

    public List<BooksCategories> BookCategoriesObj { get; set; }


}

我的想法是,当用户首次注册到某个应用程序时,他/她被重定向到一个表单页面,通过勾选他喜欢的类别来完成他的个人资料。视图中的类别将从数据库中填充。

然而,当我进行迁移时,我得到了以下结果:

migrationBuilder.CreateTable(
            name: "BooksCategories",
            columns: table => new
            {
                BookCategoryId = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                FirstInputId = table.Column<int>(nullable: true),
                Name = table.Column<string>(nullable: false),
                isSelected = table.Column<bool>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_BooksCategories", x => x.BookCategoryId);
                table.ForeignKey(
                    name: "FK_BooksCategories_UserFirstInput_FirstInputId",
                    column: x => x.FirstInputId,
                    principalTable: "UserFirstInput",
                    principalColumn: "FirstInputId",
                    onDelete: ReferentialAction.Restrict);
            });

该框架在BookCategories表中添加了另一个名为FirstInputId的列,该列依赖于FirstInput模型中的索引器。这严重搞砸了我的用户生成的条目。我不希望用户数据存储在BooksCategories表中,我只想从db中获取它。然后,它们将作为多个答案保存在FirstInput表中的字符串中。

我做错了什么? 附:我试图找到类似的东西,但没有什么接近我遇到的问题。

1 个答案:

答案 0 :(得分:0)

  

我的想法是,当用户首次注册到某个应用程序时,他/她会被重定向到一个表单页面,通过勾选他最喜欢的类别来完成他的个人资料。

为什么不将这些偏好设置存储在表ApplicationUser中?它会创建该外键,因为您配置了一对多关系。对于您的模型,A FirstInput有很多BookCategory。为什么将isSelected存储在数据库中,但是......?

我的解决方案FirstInput不应存储在数据库中。相反,将其视为视图的InputModel 。在视图中,如果用户选择名为Horror Books的单选按钮,请找到ID并添加到列表FirstInput.BookCategoriesObj,依此类推。

重新设计数据库模型,如下所示:

public class ApplicationUser : IdentityUser
{
    ICollection<BookCategory> BookCategories { get; set; }
}

public class Book
{ ... }

public class BookCategory
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public ICollection<ApplicationUser> ApplicationUsers { get; set; }
}

现在这是多对多关系(应用程序用户可以拥有零个或多个喜欢的图书类别。类别可以是零或多个用户的最喜欢的选择)。实体框架将创建一个连接表来存储这些首选项(可能名为ApplicationUserBookCategories)。

要插入记录,只需像其他普通类型一样。或者您可以看到更多here

相关问题