C # Entity Framework - One-Stop Solution
Is there a generics solution for the following code?
public static int SaveReorder(IList<int> listItems)
{
int result = 0;
int order = 1;
Entity1 db = null;
using (ObjectContext context = new ObjectContext())
{
foreach (int id in listItems)
{
db = Get(context, id);
db.Order = order;
context.SaveChanges();
order += 1;
}
result = 1;
}
return result;
}
listItems contains an ordered sequence of identification characters. Entity1 is one of the EntityObjects from our EDM. Get (...) is a custom method in the same class to get an EntityObject based on the current ObjectContext and Id.
We want a generic solution for this implementation so that we can apply this to multiple EntityObjects where the Order property is a common property for all EntityObjects. Is it possible?
source to share
Two options come to mind, as Akash already said:
-
Or let the objects implement an interface with the "Order" property:
IEntityOrder interface {int Order {get; set; }}
partial class Entity1: EntityObject {}
partial class Entity1: IEntityOrder {public int Order {get; set; }}
-
Or use reflection to set the value of the Order property (or FieldInfo if it's a field):
PropertyInfo pi = db.GetType (). GetProperty ("Order");
pi.SetValue (db, newValue, null);
source to share
No, however in the future C # 4.0 using dynamic keywords you can do this.
Interface injection using the Order property
Currently you can have an interface with an order property implemented by each class, I'm not sure how to do this in EDM, but it shouldn't be hard.
We often face this kind of problem, which is why C # comes with dynamic type, we rely on interfaces or reflection.
source to share
OK. Thanx everything for your answers. Here's my solution.
public static int SaveReorder<T>(IList<int> listItems) where T : EntityObject
{
int result = 0;
int volgorde = 1;
T entityObject = null;
using (vgplannewEntities objectContext = new vgplannewEntities())
{
try
{
foreach (int id in listItems)
{
entityObject = objectContext.GetEntityByKey<T>(id, new String[] { });
PropertyInfo pi = entityObject.GetType().GetProperty("Volgorde");
pi.SetValue(entityObject, volgorde, null);
objectContext.SaveChanges();
volgorde += 1;
}
result = 1;
}
catch
{
result = 0;
}
}
return result;
}
source to share