InvalidOperationException:实体类型'object'需要定义一个键

时间:2016-05-23 18:16:27

标签: entity-framework

实体框架7。

[Table("Settings")]
public class Setting
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public object DefaultValue { get; set; }
    public string Classification { get; set; }
    public FacilitySettingOverride FacilitySettingOverride { get; set; }
}

[Table("FacilitySettingOverride")]
public class FacilitySettingOverride
{
    [Key]
    [ForeignKey("FacilityId")]
    public int FacilityId { get; set; }

    public object Value { get; set; }
    [ForeignKey("SettingId")]
    public int SettingId { get; set; }

    public virtual ICollection<Setting> Settings { get; set; }
}

[Table("Facilities")]
public class Facility
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public  virtual ICollection<FacilitySettingOverride> FacilitySettingOverrides { get; set; }
}

运行代码时

 private IEnumerable<FacilitySettingOverride> GetFacilityBandwidthSettings
    {
        get
        {
            List<FacilitySettingOverride> settingList;
            using (SettingDbContext context = new SettingDbContext())
            {
                settingList = context.FacilitySettingOverride.ToList();
            }
            return settingList;
        }
    }

然后得到例外:

  

InvalidOperationException:实体类型'object'需要定义一个键。

背景是:

public class SettingDbContext : DbContext
{
    public DbSet<Setting> Settings { get; set; }
    public DbSet<FacilitySettingOverride> FacilitySettingOverride { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Data Source=13.53.63.74;Initial Catalog=AAAAA;User ID=sa;password=password);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

    }
}

但是,如果我在POCO中将object更改为ValueDefaultValue的字符串,则无异常。但是数据库中的类型是sql_variant。我必须使用object类型。

1 个答案:

答案 0 :(得分:0)

似乎尚未支持数据注释,因此您需要使用Fluent API进行配置。

请参阅:https://github.com/aspnet/EntityFramework/issues/1913#issuecomment-86662854