实体框架代码优先为id列添加空值

时间:2011-07-13 08:24:08

标签: entity-framework asp.net-mvc-3 entity-framework-4 entity-framework-4.1 code-first

我首先使用Entity Framework代码和ASP.NET MVC 3。

我定义了以下上下文:

public class PbeContext : DbContext
{
     public DbSet<Category> Categories { get; set; }

     protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
     {
          dbModelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
     }
}

我的分类:

public class Category
{
     public int Id { get; set; }
     public string Name { get; set; }
     public string Description { get; set; }
     public string MetaKeywords { get; set; }
     public string MetaDescription { get; set; }
     public bool IsActive { get; set; }
     public Category ParentCategory { get; set; }
     public int ParentCategoryId { get; set; }
}
我的ParentCategoryId中的

Category table是一个链接到Id(类别ID)列的外键。

在我的创建视图中,有一个显示所有父类别的删除列表。您不必选择父类别。如果未选择,则表示您正在创建/捕获父类别。

我过去常常做的是,如果用户没有从下拉列表中选择父类别,那么我会在ParentCategoryIdCategory中设置NULL。目前它正在尝试向表中添加0并失败,因为没有类别和Id为0.如果没有选择父类别,是否仍然是将其添加为NULL值的最佳做法?如果是这样,我将如何首先使用Entity Framework代码?

修改

我已将视图模型和Category类中的int更改为可建议的nullable。

public class CreateCategoryViewModel
{
    public CreateCategoryViewModel()
    {
        IsActive = true;
    }

     public string Name { get; set; }
     public string Description { get; set; }
     public string MetaKeywords { get; set; }
     public string MetaDescription { get; set; }
     public bool IsActive { get; set; }
     public SelectList ParentCategoriesSelectList { get; set; }
     public int? ParentCategoryId { get; set; }
}

我更新的类别类:

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string MetaKeywords { get; set; }
    public string MetaDescription { get; set; }
    public bool IsActive { get; set; }
    public int? ParentCategoryId { get; set; }
}

我的下拉列表有一个默认的“ - 选择 - ”选项,其值为0.当我单击提交时,视图模型中的ParentCategoryId为0.我将其映射到类别类,而ParentCategoryId仍为零。何时以及如何将其转换为NULL?我仍然得到的错误是:

The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Category_Category". The conflict occurred in database "ProgrammingByExample", table "dbo.Category", column 'Id'.
The statement has been terminated.

1 个答案:

答案 0 :(得分:1)

ParentCategoryId可以为空

public class Category
{
     public int Id { get; set; }
     public string Name { get; set; }
     public string Description { get; set; }
     public string MetaKeywords { get; set; }
     public string MetaDescription { get; set; }
     public bool IsActive { get; set; }
     public Category ParentCategory { get; set; }
     public int? ParentCategoryId { get; set; }
}

修改

  

我的下拉列表有一个默认的“ - 选择 - ”选项,其值为0

默认选项不应该有一个值(你已经把0) 例如:

@Html.DropDownFor(model => model.ParentCategoryId, 
    (SelectList)ViewBag.ParentCategories, "-- Select --")