【发布时间】:2016-02-02 07:49:13
【问题描述】:
我想做这样的事情:
获取Entity Framework 中Entity 的列名。
我不想直接使用 Entity Name ,我想将 Entity-Name 作为字符串传递给方法。
public HttpResponseMessage GetColumnName(string MyClassName)
{
var db = new DAL.MyEntities();
var names = typeof(db.MyClassName).GetProperties()
.Select(property => property.Name)
.ToArray();
return new HttpRequestMessage().CreateResponse(HttpStatusCode.OK, names, new HttpConfiguration().Formatters.JsonFormatter);
}
注意:我不想使用switch-case 或If-else。
为什么我需要这个? 我必须将 API 中的数据作为 JSON 返回。 我们创建了一个将实体模型转换为我们的类的方法,没有任何关系:
实体类:
public partial class foo
{
public foo()
{
this.parent = new HashSet<parent>();
this.child = new HashSet<child>();
}
public int id { get; set; }
public string title { get; set; }
public virtual ICollection<parent> parent { get; set; }
public virtual ICollection<child> child { get; set; }
}
我想调用这个 API:
public HttpResponseMessage GetFooData()
{
var db = new DAL.MyEntities();
var data = db.foos.ToList();
return new HttpRequestMessage().CreateResponse(HttpStatusCode.OK, data, new HttpConfiguration().Formatters.JsonFormatter);
}
如果我返回 List<foo> data 将收到此错误:
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.
要解决这个问题,我必须创建另一个与实体模型相同的模型,而没有像这样的任何子级和父级:
public partial class Myfoo
{
public int id { get; set; }
public string title { get; set; }
}
然后我将循环 List<foo> 并填写 List<Myfoo> ,然后我将返回 List<Myfoo>。
现在创建这个类每天都在浪费我的时间,我想创建一个生成器来创建MyFoo 和生成器来用List<Foo> 填充Lis<MyFoo>。
【问题讨论】:
-
您能解释一下您为什么要实现这一目标吗?也许还有其他可能性需要考虑。
-
我在网上搜索其他方法,但我找不到任何方法。
-
看看automapper.org 或github.com/omuleanu/ValueInjecter。如果属性名称相同,这些框架会将值从 Foo 填充到 MyFoo 类
-
我的问题是从
MyFoo实体创建MyFoo类。
标签: c# entity-framework ef-model-first