使用字符串作为DbSet类型,如DbSet< string>在EF-CodeFirst中 [英] Use string as type of DbSet like DbSet<string> in EF-CodeFirst

查看:1146
本文介绍了使用字符串作为DbSet类型,如DbSet< string>在EF-CodeFirst中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to have a list of string and save and load them to/from database using EF-CodeFirst. this is my DbContext class:

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

但是当我尝试运行代码时,我得到这个异常: System.InvalidOperationException 类型System.String未映射。使用Ignore方法或NotMappedAttribute数据注释检查类型是否未被显式排除。验证类型是否被定义为类,不是原始的,嵌套的或通用的,并且不继承自EntityObject。

but when I try to run the code I get this exception: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.

解决问题?

推荐答案

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

You cannot have a DbSet<string>. String is treated as a primitive type by EF and the type for the DbSet has to be an entity. Entity has properties (which usually are mapped to columns in database) and also have to have keys. If, in your database you have a table that has just one string column you would have to create an entity with a string property to model this. In addition the string property will have to be a key property.

这篇关于使用字符串作为DbSet类型,如DbSet&lt; string&gt;在EF-CodeFirst中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆