如何通过Fluent API更改数据库列名

时间:2016-02-25 22:53:38

标签: entity-framework ef-fluent-api

我有以下代码:

public abstract class Entity
{
    public virtual int Id { get; set; }
}

public class Category : Entity
{
    public string Name { get; set; }
    public virtual ICollection<Category> Children { get; set; }
    public virtual ICollection<Item> Items { get; set; }
}

public class Item : Entity
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public DateTime DateCreated { get; set; }
    public virtual Category Category { get; set; }
}

此语法

modelBuilder.Entity<Category>().Property(x => x.Children).HasColumnName("CategoryID");

给我严重程序代码描述项目文件行 错误CS0453类型&#39; ICollection&#39;必须是不可为空的值类型才能将其用作参数&#39; T&#39;在泛型类型或方法中&#39; StructuralTypeConfiguration.Property(Expression&gt;)&#39;

问:如何通过Fluent API更改数据库列名?

1 个答案:

答案 0 :(得分:0)

集合本身无法映射到一列。您应该将其映射为一对多关联:

modelBuilder.Entity<Category>()
            .HasMany(c => c.Children)
            .WithOptional()
            .Map(m => m.MapKey("CategoryID"));