I have a casting issue and I was wondering if anyone would be able to help me see how I can fix this issue?
Basically I'm trying to create a CSV generator console program that will take a list of machine records from the DB and put them into a CSV.
The code below is simplified but generally similar to my implementation currently:
public interface IRecord
{
}
public class MachineRecord : IRecord
{
string Name {get;set;}
string ErrorCount {get;set;}
}
public interface IRecordStore
{
string GenerateRecord(IRecord record);
}
public class CSVMachineRecordStore : IRecordStore
{
public string GenerateRecord(IRecord record)
{
var machineRecord = (MachineRecord)record;
var strBuilder = new StringBuilder();
strBuilder.Append(machineRecord.Name);
strBuilder.Append(machineRecord.ErrorCount);
return strBuilder.ToString();
}
}
So basically here I've created a class that inherits from IRecordStore, and in our case we have to create an implementation of GenerateRecord. The problem here is I have to cast the record of be of type MachineRecord or the compiler will throw a casting error out, this is due to Record not having any properties set.
Is it possible to not have the direct cast in this implementation so this line of code will be like:
public class CSVMachineRecordStore : IRecordStore
{
public string GenerateRecord(IRecord record)
{
var machineRecord = record; //we want to remove the explicit cast
var strBuilder = new StringBuilder();
strBuilder.Append(machineRecord.Name);
strBuilder.Append(machineRecord.ErrorCount);
return strBuilder.ToString();
}
}
I know I can fix this issue by adding Name and ErrorCount properties to IRecord, but IRecord is a very generic interface that can have anything.
We want to be able to create a CSV program that can handle machine records, customer records, employee records, supplier records, etc...
I'm thinking of using generics, and I've played with them a bit but I've had some trouble getting it to work too.
Use generics:
public interface IRecordStore<T> where T:IRecord
{
string GenerateRecord(T record);
}
Then implement:
public class CSVMachineRecordStore : IRecordStore<MachineRecord>
{
public string GenerateRecord(MachineRecord record)
{
var machineRecord = record; //we want to remove the explicit cast
var strBuilder = new StringBuilder();
strBuilder.Append(machineRecord.Name);
strBuilder.Append(machineRecord.ErrorCount);
return strBuilder.ToString();
}
}
I wrote this in a hurry, make sure to check for silly errors.
The type casting exception occurs when the IRecord instance is not an instance of MachineRecord.
To answer your question how to fix the casting issue, you should have a look at the as operator.
However, for me this looks like making the IRecordStore interface generic could help you prevent the type issues you're experiencing:
[Edit] I noticed since IRecordStore is an interface you could even make the generic type contravariant. This allows you to assign a variable
of type IRecordStore<IRecord> with an instance of IRecordStore<MachineRecord> or more explicitly CSVMachineRecordStore.
public interface IRecordStore<in T> where T : IRecord
{
string GenerateRecord(T record);
}
public class CSVMachineRecordStore : IRecordStore<MachineRecord>
{
public string GenerateRecord(MachineRecord record)
{
var machineRecord = record;
var strBuilder = new StringBuilder();
strBuilder.Append(machineRecord.Name);
strBuilder.Append(machineRecord.ErrorCount);
return strBuilder.ToString();
}
}
Related
How Can I dynamically cast at runtime.That is I am passing a child class object in the parent class object.
public abstract class tObject
{
public tObject[] someMthode(){;}
}
public class myClass : tObject
{
public string Oth0 { get; set; }
public string Oth1 { get; set; }
public string Oth2 { get; set; }
}
I want
myClass mc=new myClass();
tObject to=mc;
myClass[] mcArray=(myClass[])mc.someMthode();//System.InvalidCastException
//Unable to cast object of type 'tObject[]' to type 'myClass[]'
but when check any element of mcArray is correct
if (mcArray[0] is myClass)
{
//return true and run this ;
}
In fact I want cast when a method return array of tObject according to the base class :
subClass[] mcArray=(subClass[])instanceOfsubClass.someMthode()
subClass or myClass and ... are unknown class , and i don't know theirs name.
Solution
public T[] Cast<T>(tObject[] mcArray ) where T : tObject
{
if (mcArray != null)
{
int cnt = mcArray.GetLength(0);
T[] t = new T[cnt];
for (int i = 0; i < cnt; i++)
{
t[i] = (T)mcArray[i];
}
return t;
}
return null;
}
Thanks all for replies.
C# does not support that kind of array conversion. C# does -- unfortunately! -- support dangerous array covariance. That is, if you had an array myClass[] then you could implicitly convert it to an array tObject[]. This means that you can do this:
Tiger[] tigers = new Tiger[10];
Animal[] animals = tigers;
animals[0] = new Turtle();
and now we have a turtle inside an array of tigers. This crashes at runtime.
That's bad enough, but you want it to go the other way -- I have an array of animals and I'd like it to be treated as an array of tigers. That does not work in C#.
As other answers have noted, you'll need to make a second array and copy the contents of the first to the second. There are a number of helper methods to do so.
Maybe?
myClass mc = new myClass();
tObject to = mc;
//myClass[] mcArray = (myClass[])mc.someMthode();//System.InvalidCastException
//Unable to cast object of type 'tObject[]' to type 'myClass[]'
var mcArray = Array.ConvertAll(mc.someMthode(), item => (myClass) item);
Well, you can call IEnumerable.Cast for that:
var myArr = mc.someMethod().Cast<MyClass>().ToArray();
As MyClass[] implements IEnumerable<MyClass>.
EDIT: What you want is quite dangerous. Look the following code:
subClass[] mcArray=(subClass[]) new BaseClass[] {...};
If this conversion would work we could now simply make the following also:
mcArray[0] = new AnotherClass();
Now you have an array of subClasses containin one item of AnotherClass also.
If you do not know the type at compile-time you cannot expect the compiler to provide any compile-time-logic for a type it doesn´t know. Thus casting to an unknown type and calling members on isn´t supported. However you may achieve this using reflection:
var runtimeType = myArr[0].GetType();
var mi = runtimeType.GetMethod("SomeMethod");
var value = mi.Invoke(myArr[0]);
This is similar to the call
var value = ((subClass)myArr[0]).SomeMethod();
Why not solve it one step up the chain and make someMethod (spelling corrected) generic:
public abstract class tObject<T> where T:tObject
{
public T[] someMethod(){;}
}
public class myClass : tObject<myClass>
{
public string Oth0 { get; set; }
public string Oth1 { get; set; }
public string Oth2 { get; set; }
}
now myClass.someMethod returns a myclass[] and that problem is solved. However, since I'm assuming that tObject does other things that just create an array of tObjects, it may cause other problems that aren't inferrable from the code you provided.
Plus it's not 100% foolproof. There's nothing stopping you (or someone else) from defining:
public class myWeirdClass : tObject<myClass>
{
}
now myWeirdClass.someMethod also returns a myClass[], and the pattern is broken. Unfortunately there's no generic constraint that requires that the generic parameter be the defining class itself, so there's no way to prevent this flaw at compile-time.
Another option may be to move the array creation outside of the class itself, since it is a code smell in itself:
public class ObjectFactory<T> where T:tObject
{
public T[] SomeMethod()
{
... create an array of Ts
}
}
Hi I have a simple issue with an sql application that I seem not to be capable of resolve. It involves the use of generics of which I am not too familiar with. I did researches here and on-line but I do not seem to find a fitting solution for my case.
I have two classes: Table and Field. I want Table to contain a List of Field and I want each Field to contain a List of RecordSet. The tricky part is that I want the user to choose which type of RecordSet to implement.
The Class Definition of Table is:
namespace DBlib
{
public class DBTable<T>
{
public List<DBField<T>> FieldName = new List<DBField<T>>();
public DBTable (string NameOfTable)
{
}
public void AddField (string Name)
{
DBField<T> TempList = new DBField<T>();
FieldName.Add(TempList);
}
}
}
The Class Definition of Field is:
namespace DBlib
{
public class DBField<T>
{
public List<T> RecordSet = new List<T>();
public DBField()
{
}
}
}
With this code the user is forced cast the type when he is instantiating DBTable. This is not correct. I want the user to cast the type when the AddField method is invoked. Can you suggest a simple way to solve this issue?
UPDATE #1
I changed TempList as DBField in the Table Class definition. Sorry for the confusion there.
I want to add also this code to explain better what my issue is. Assuming the first Field of the table is an integer, the user should do:
namespace SpecifytheName
{
public class User
{
DBTable<int> Table = new DBTable<int>();
public User()
{
}
}
}
Instead, I want the user to do:
namespace SpecifytheName
{
public class User
{
DBTable Table1 = new DBTable("Table1");
// SPECIFY THE TYPE OF FIELD1 ONLY AT THIS POINT
Table1.AddField<int>("Field1"); //or something like this
public User()
{
}
}
}
I would generally solve this issue using a non-generic interface to store your fields.
So start with this interface:
public interface IDBField
{
IList RecordSet { get; }
Type FieldType { get; }
}
Now implement DBField<T> like this:
public class DBField<T> : IDBField
{
public List<T> RecordSet = new List<T>();
IList IDBField.RecordSet
{
get
{
return this.RecordSet;
}
}
Type IDBField.FieldType
{
get
{
return typeof(T);
}
}
}
Then you can implement DBTable like this:
public class DBTable
{
public List<IDBField> FieldName = new List<IDBField>();
public void AddField<F>(string Name)
{
FieldName.Add(new DBField<F>());
}
}
You can use the FieldType property on IDBField to determine the type of the field and then use reflection as necessary to use the values of RecordSet appropriately.
The only way I can see this working is by not using Generics, but just use the Object class.
for example:
public class DBTable
{
public List<DBField<Object>> FieldName = new List<DBField<Object>>();
public DBTable (string NameOfTable)
{
}
public void AddField(string Name)
{
List<DBField<Object>> TempList = new List<DBField<Object>>();
FieldName.Add(TempList);
}
}
This will mean you can use any type in the RecordSet object without restricting the type in the DBTable class.
I could be a bit off base here as I'm not sure what you're trying to achieve, for one you aren't going anything with the Name parameter passed into the AddField method, and you're TempList object isn't the same type as FieldName so it should throw some errors there..
EDIT:
I think I understand more clearly what you're trying to do, try this -
public class DBTable
{
public List<DBField<Object>> FieldName = new List<DBField<Object>>();
public DBTable (string NameOfTable)
{
}
public void AddField<FieldType>(string Name)
{
DBField<FieldType> field = new DBField<FieldType>(Name);
FieldName.Add(field);
}
}
This way each Field (Column) is still forced to a type, but the DBTable isn't tied down to that same type.
I've coded myself into a corner and would like your help to dig me out again. In the right direction.
So, I've implemented a minor SQLite wrapper where I wanted the solution to be generic (don't we all). Afterwards, I now realize that the usage of these classes and interfaces aren't very intuitive nor generic.
Let's start at the bottom and work upwards. I've created a class called DataRow that works as a base class for my table rows. The class DataRow itself only has a property Id (since all rows need one). This results in the following definition: class DataRow { public int Id { get; set; } }
Using this DataRow class, is each table. And for database tables I've created one generic interface, and one generic base class. The definitions looks like this:
internal interface ITable<T>
where T : DataRow, new()
{
T Select(int id);
List<T> Select(List<int> ids);
int Insert(T t);
void Update(T t);
bool Delete(int id);
}
public class Table<T> : ITable<T>
where T : DataRow, new()
{
// Commented out to protect you from a minor case of serious brain damage.
}
This setup allows me to create concise definitions. In fact, they tend to be quite epic, really. Proud to say.
public class Car : DataRow
{
public decimal ParkingTicketDebt { get; set; }
public DateTime WhenWifeWillAllowReplacement { get; set; }
public bool CanTransformIntoSomethingAwesome { get; set; }
}
public class Cars : Table<Car> {
// Yep, that's all. You can go home now, folks. There's nothing here. Nothing at all. Especially not a great treasure of gold. Whops... I mean... there's really not. Not that I'm aware of, anyway... I mean, there could be. Not that I wouldn't say if I had any information on this great trasure of gold that might exist. But I know nothing of such an item. I really don't, so you can stop thinking about this great treasure of gold. Since I don't know anything about it, the chance that it even exist is extremely low. Miniscule. I mean, you would probably not find anything, not even if you digged for, like, a really long time. Seven years or something. Oookay. Slowly fading away...
}
As you may or may not have noticed, I'm using the class type name of Cars to determine the name of the table in the database. Likewise, I'm performing reflection on Car and use its public property names and types to get/set values in the database. And yes, I'm aware that I'm in the process of coding a stripped down version of Entity Framework. Which sounds both really stupid and quite time consuming.
Anyway, here is a usage example of the class Cars, which I must remind you that I'm proud of:
new Cars().Delete(3497); // Note that I have a great number of (expensive) cars.
Nice, eh? One slight problem. This means that I have to write strongly typed code, specific to the number of tables that exist in the database. And I don't like specific code. I like generic code.
You might start arguing here that I'm overdoing it. Then let me tell you this. You're damn right I'm overkilling! I'm intentionally flamethrowing the dead guy that was ran over by a tank. Seven times.
So I started experimenting a bit and came up with this delicate solution:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(EnableSession = true)]
public int CreateEmptyRow(string tableName)
{
var tableType = Type.GetType(tableName);
if (tableType == null)
throw new TypeLoadException("Dumbass. That table doesn't exist");
var instance = Activator.CreateInstance(tableType) as ITable<dynamic>;
if (instance == null)
throw new TypeLoadException("Idiot. That type isn't a table");
return instance.Insert(new DataRow());
}
Note that I can really understand if you have no idea why someone would want to create an empty row.
So what's wrong with this? Well, it doesn't compile, for one. Here's the error: There is no implicit reference conversion from 'dynamic' to 'DataRow'. A search on Google gave few results.
The problem is obviously Activator.CreateInstance(tableType) as ITable<dynamic>. I've tried things like Activator.CreateInstance(tableType) as ITable<Table<DataRow>>, an attempt which gave me this error: The type 'DataRow' must be convertible to 'DataRow'.
So, as ive written in the comment, Im adding an extra non-generic interface:
interface ITable
{
DataRow Select(int id);
IEnumerable<DataRow> Select(List<int> ids);
int Insert(DataRow t);
void Update(DataRow t);
}
interface ITable<T> where T : DataRow, new()
{
T Select(int id);
List<T> Select(List<int> ids);
int Insert(T t);
void Update(T t);
bool Delete(int id);
}
class Table<T> : ITable<T>, ITable where T : DataRow, new()
{
public T Select(int id)
{
return new T();
}
public List<T> Select(List<int> ids)
{
return new List<T>();
}
public int Insert(T t)
{
return 1;
}
public void Update(T t)
{
}
public bool Delete(int id)
{
return true;
}
DataRow ITable.Select(int id)
{
return this.Select(id);
}
IEnumerable<DataRow> ITable.Select(List<int> ids)
{
return this.Select(ids);
}
public int Insert(DataRow t)
{
return this.Insert(t);
}
public void Update(DataRow t)
{
this.Update(t);
}
}
and this is how im implementing the CreateEmptyRow \ Select methods:
public static int CreateEmptyRow(string tableName)
{
var tableType = Type.GetType(tableName);
if (tableType == null)
throw new TypeLoadException("Dumbass. That table doesn't exist");
var instance = Activator.CreateInstance(tableType) as ITable;
if (instance == null)
throw new TypeLoadException("Idiot. That type isn't a table");
return instance.Insert(new DataRow());
}
public static List<DataRow> Select(List<int> ids, string tableName)
{
var tableType = Type.GetType(tableName);
if (tableType == null)
throw new TypeLoadException("Dumbass. That table doesn't exist");
var instance = Activator.CreateInstance(tableType) as ITable;
if (instance == null)
throw new TypeLoadException("Idiot. That type isn't a table");
return instance.Select(ids).ToList();
}
notice that if you want such a generic solution, the select method (for example) can only return an IEnumerable \ List of DataRow, which can be solved by using the provided Cast extension method:
var myList = Select(null, "Cars").Cast<Car>();
Note: as you probably know, to instantiate the Cars class by name, you also need to provide the namespace, which i skipped here, and probably the Table<T> class should be abstract as well.
One problem is you're trying to insert a DataRow into a table which takes some subclass of DataRow, so even if you could compile it, you would still get an exception at runtime.
You need to find the generic row type to insert and insert a new instance of that type:
object instance = Activator.CreateInstance(tableType);
var tableInterface = tableType.GetInterfaces().FirstOrDefault(it => it.IsGenericType && it.GetGenericTypeDefinition() == typeof(ITable<>));
if(tableInterface == null) throw new ArgumentException("Type is not a table type");
var rowType = tableInterface.GetGenericArguments()[0];
var newRow = Activator.CreateInstance(rowType);
MethodInfo insertMethod = tableInterface.GetMethod("Insert");
return (int)insertMethod.Invoke(instance, new object[] { newRow });
However it seems you could make your CreateEmptyRow method generic in the table and row type and avoid reflection altogether:
public int CreateEmptyRow<TTable, TRow>()
where TRow : DataRow, new()
where TTable : ITable<TRow>, new()
{
var table = new TTable();
return table.Insert(new TRow());
}
I'm trying to figure out how I can make a Generics call take a variable for the Type. In the call below it take a type "DAL.Account" and works fine.
var tst = ctx.GetTable<DAL.Account>().Where(t => t.Sbank == "000134");
I want to change that so that I can pass a variable in place of the "DAL.Account". Something like this but I know that won't work as you can't pass property as a Type.
ctx.GetTable<Criteria.EntityType>().Where(LinqToSQLHelper.BuildWhereStatement(Criteria.StateBag), Criteria.StateBag.Values.ToArray())
Below is the shell pieces of code I think explains what I'm trying to do. Generics is not my strong suit so I'm looking for some help. Is there anyway that I can make this happen?
//Stores a "Type" that indicates what Object is a Criteria for.
public class AccountCriteria : IGeneratedCriteria
{
...
public Type EntityType
{
get {return typeof(DAL.Account);}
}
}
//I have added a function to the DataContext called "GetTable"
// And then used it as an example in a Console App to test its functionality.
public class ADRPDataContext : NHibernateDataContext
{
...
public CodeSmith.Data.NHibernate.ITable<T> GetTable<T>() where T : EntityBase
{
var tb = new CodeSmith.Data.NHibernate.Table<T>(this);
return tb;
}
}
// console application that uses DataContext.GetTable
class Program
{
static void Main(string[] args)
{
using (var ctx = new ADRPDataContext())
{
var tst = ctx.GetTable<DAL.Account>().Where(t => t.Sbank == "000134");
}
}
}
//ExistsCommand class that uses the EntityType property of the Critera to generate the data.
public class ExistsCommand
{
private IGeneratedCriteria Criteria { get; set; }
protected override void DataPortal_Execute()
{
using (var ctx = new DC.ADRPDataContext())
{
//This was my first attempt but doesn't work becuase you can't pass a property in for a Type.
//But I can figure out how to write this so that it will work.
Result = ctx.GetTable<Criteria.EntityType>().Where(LinqToSQLHelper.BuildWhereStatement(Criteria.StateBag), Criteria.StateBag.Values.ToArray()).Count() > 0;
}
}
}
You are looking to instantiate a generic type. Some info can be found here
This is a simple example demonstrating how to instantiate a List with a capacity of 3. Here is a method that you can call to create a generic when you don't know the type:
public static Object CreateGenericListOfType(Type typeGenericWillBe)
{
//alternative to the followin:
//List<String> myList = new List<String>(3);
//build parameters for the generic's constructor (obviously this code wouldn't work if you had different constructors for each potential type)
object[] constructorArgs = new Object[1];
constructorArgs[0] = 3;
//instantiate the generic. Same as calling the one line example (commented out) above. Results in a List<String> with 3 list items
Type genericListType = typeof(List<>);
Type[] typeArgs = { typeGenericWillBe };
Type myNewGeneric = genericListType.MakeGenericType(typeArgs);
object GenericOfType = Activator.CreateInstance(myNewGeneric, constructorArgs);
return GenericOfType;
}
And here is some sample code that will show you the example method works:
List<String> Strings = (List<String>)InstantiateGenericTypeWithReflection.CreateGenericListOfType(typeof(String));
//demonstrate the object is actually a List<String> and we can do stuff like use linq extensions (isn't a good use of linq but serves as example)
Strings.Add("frist");
Strings.Add("2nd");
Strings.Add("tird");
Console.WriteLine("item index 2 value: " + Strings.Where(strings => strings == "2").First());
In your example, replace your GetTable<Criteria.EntityType>() with CreateGenericTableOfType(Criteria.EntityType). This will return a generic table of whatever type you pass in. You will of course need to implement the method properly (handle constructor args, change List to Table etc).
I think you need to change the way you're doing this slightly, and instead use generics instead of the EntityType property. Perhaps something along the lines of the following:
// Create an abstract class to be used as the base for classes that are supported by
// ExistsCommand and any other classes where you need a similar pattern
public abstract class ExtendedCriteria<T> : IGeneratedCriteria
{
public ExistsCommand GetExistsCommand()
{
return new ExistsCommand<T>(this);
}
}
// Make the non-generic ExistsCommand abstract
public abstract class ExistsCommand
{
protected abstract void DataPortal_Execute();
}
// Create a generic sub-class of ExistsCommand with the type parameter used in the GetTable call
// where you were previously trying to use the EntityType property
public class ExistsCommand<T> : ExistsCommand
{
protected override void DataPortal_Execute()
{
using (var ctx = new DC.ADRPDataContext())
{
Result = ctx.GetTable<T>().Where(LinqToSQLHelper.BuildWhereStatement(Criteria.StateBag), Criteria.StateBag.Values.ToArray()).Count() > 0;
}
}
}
// Derive the AccountCriteria from ExtendedCriteria<T> with T the entity type
public class AccountCriteria : ExtendedCriteria<DAL.Account>
{
...
}
I would like find a workaround to accomplish a simple solution in order to automatize certain operation through EF.
What I need it's takeover during saving and retrieving process to modifying query result, but this class will be able to make that work for any type entities.
Example: I have a MyTestDb. So in my C# project I create a new entity model (MyTEstDbModel.edmx), with relative POCO class generation.
Well, a point of interest could be implementing a new custom class like following:
class Example
{
private ObjectContext _context;
private Example(ObjectContext obj) { _context = obj; }
public void Store(ObjectSet<???generic???> os)
{
// problem here: I dont't know the type contained in ObjectSet
// but if I Knew its type, I could make a work like this:
// -> foreach every instance in objectSet to check if exist some property
// via reflection, if i found them, then I set always the same values.
// Why this? Because all my db contains some common filed
// like (createdByUser, TimeToUpdate, and so on..), so it wold be boring
// setting all those fileds from any point of program.
}
public void Retrive(ObjectSet<???generic???> os)
{
// here problem too: all my queries will be filtered by one or more value
// fileds, but I cannot use lambaExpression cos I don't Know the type
// contained in objectSet<..>
}
//....
finally, by any point of program, the code should appear like following:
Example obj = new Example(myEntityContext); //-> global
var result = myEntityContext.ObjectSetTyped.Where(..lambaExpression..condition)
result.someProperty = "...";
obj.Store(result); // store method will fill all other boring filed automatically.
Can anyone give me some tips, help, suggestion about my issue?
Thanks in advance...
Update
Now, just only another problem. I'd to filter my ObjectSet through retrieve method like following:
public void Retrieve<TEntity>(IQueryable<TEntity> ooo) where TEntity : IC
{
ooo = ooo.Where(p => p.Filed == "MyDefaultValue");
}
But, from external method, not objectSet result is affect by my filter.
How so..?
MyEntities ent = new...
MyWrapper wrap = new MyWrapper();
wrap.Retrieve(ent.Users);
//problem here -> users objectSet is always the same..
Define interfaces which will allow you to do this. For example:
public interface IEntity
{
DateTime CreatedAt { get; set; }
string CreatedBy { get; set; }
}
You need to "implement" this interface in your entities. You can for example either modify T4 template generating entities or implement it in partial class. Both properties must be already defined in the model so the implementation is only declarative:
public partial class MyEntity : IEntity // That's all
{ }
Now you can define Store like:
public void Store<TEntity>(TEntity entity) where TEntity : IEntity
{
...
}
Same can be done with query but you can for example define custom extension method:
public static IQueryable<TEntity> GetUserEntities(this IQueryable<TEntity> query, string user)
where TEntity : IEntity
{
return query.Where(e => e.CreatedBy == user);
}
You will simply define your query like:
var result = myEntityContext.MyEntities.GetUserEntities("someName");
Other approach is defining simply GetQuery on your custom context:
public IQueryable<T> GetQuery<T>() where T : IEntity
{
var query = GetObjectSetSomehow;
return query.ApplyGlobalConditions(); // Just another extension with your conditions
}
I'm not a big fan of the repository pattern but generally what you are trying to do is close to generic repository so check for example this post. It is just some example which can be further extended.
yeah, I just want a generic approach, likewise I realized with dataset and datatable.. but it seems impossible to achieve..
..ehmm..however, let me show yuo following code snippet, dynamic keyword looks like something to hopeful.... maybe I'm colse to solution..?
public ObjectSet<dynamic> Retrieve(string entity, string context)
{
Type myObjectContextType = Type.GetType(context);
ConstructorInfo cs = myObjectContextType .GetConstructor(new Type[] { });
dynamic myObjContext = cs.Invoke(new object[] { });
Type t = Type.GetType(entity);
ConstructorInfo xi = t.GetConstructor(new Type[] { });
dynamic UserEntity = xi.Invoke(new object[] { });
!problem here!
ObjectSet<?????> os = myObjContext.UserEntity.Where(...)
return ...
}
I'm very surprised..EF is a great instruments to develope more efficiently ways but too little "generalizalbe"