获取实体框架模型第一个实体名称动态

时间:2016-02-02 07:49:14

标签: c# entity-framework ef-model-first

我想做这样的事情: 在Entity中获取Entity Framework的列名。

我不想直接使用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-caseIf-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'.

要解决这个问题,我必须创建另一个与Entity模型相同的模型,而没有像这样的子和父:

public partial class Myfoo
{
    public int id { get; set; }
    public string title { get; set; }

}

然后我会循环List<foo>并填写List<Myfoo>,然后我将返回List<Myfoo>

现在创建这个课每天浪费我的时间,我想创建一个创建MyFoo的生成器和生成Lis<MyFoo> List<Foo>的生成器。

2 个答案:

答案 0 :(得分:1)

如果您有标准定义的DbContext

public class MyEntities : DbContext
{
    //..
    public DbSet<MyEntity> MyEntites { get; set; }

    //..
}

你需要使用反射

var db = new DAL.MyEntities();
var type = db.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
                       .Where(pr => pr.PropertyType.IsGenericType)
                       .Where(pr => pr.PropertyType.GetGenericTypeDefinition() ==  
                                           typeof(DbSet<>))
                       .Select(pr => pr.PropertyType.GetGenericArguments().Single())
                       .SingleOrDefault(t => t.Name == MyClassName);
if (type == null) / * type not found case */ ;

var names = type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                .Select(property => property.Name)
                .ToArray();

答案 1 :(得分:0)

我的问题已解决,如下所示:

--force-*

我从实体获取所有属性,请注意public List<string> GetServiceModelProprty(string EntityName, bool ShowGeneric = false) { List<string> ProNames = new List<string>(); var names = Type.GetType(EntityName) .GetProperties() .Select(p => p.Name).ToArray(); ProNames.AddRange(names); return ProNames; } 应包含NameSpace,如:EntityName

这也是我的mapper生成器:

DAL.MyClassName