【问题标题】:Use string as type of DbSet like DbSet<string> in EF-CodeFirst使用字符串作为 DbSet 的类型,如 EF-Code First 中的 DbSet<string>
【发布时间】:2012-10-21 18:20:58
【问题描述】:

我想要一个字符串列表,并使用 EF-CodeFirst 将它们保存到数据库或从数据库加载它们。这是我的 DbContext 类:

public class KeysDbContext : DbContext
{
    public DbSet<string> Keys { get; set; }
}

但是当我尝试运行代码时,我得到了这个异常:System.InvalidOperationException : The type 'System.String' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.

我该如何解决这个问题?

【问题讨论】:

    标签: c# entity-framework c#-4.0 ef-code-first


    【解决方案1】:

    您不能拥有DbSet&lt;string&gt;。 EF 将 String 视为原始类型,并且 DbSet 的类型必须是实体。实体具有属性(通常映射到数据库中的列)并且还必须具有键。如果在您的数据库中,您有一个只有一个字符串列的表,您将必须创建一个具有字符串属性的实体来对此进行建模。此外,字符串属性必须是键属性。

    【讨论】:

    • 谢谢。还有一个问题:如何让 EF-CodeFirst 自己生成密钥?
    • 你的意思是数据库对吧? EF 不生成密钥 - 您必须设置密钥值或让数据库为您生成它。对于 int 键,EF 默认创建标识列。您可以使用 DatabaseGeneratedAttribute 更改它。
    猜你喜欢
    • 2011-08-17
    • 2012-11-30
    • 2013-01-17
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多