I want to do something like this :
Get Column name of an Entity
in Entity Framework
.
I don't want directly using Entity Name
, I want to pass Entity-Name
to method as string.
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);
}
Note : I don't want to use switch-case
or If-else
.
Why I need this ? I have to return data in an API as JSON . We created a method that convert Entity Models to our class without any relation :
Entity Class:
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; }
}
I want to call this 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);
}
If I Return a List<foo> data
will got this error :
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.
to resolve this I have to create another model same as Entity model without any child and parent like this :
public partial class Myfoo
{
public int id { get; set; }
public string title { get; set; }
}
Then I will loop on List<foo>
and fill List<Myfoo>
, then I will return List<Myfoo>
.
Now creating this class wasting my time every day and I want to create a Generator that create MyFoo
and Generator to fill Lis<MyFoo>
with List<Foo>
.