DLinq EntityManager StartsWith method

A

Andrus

I have lot of sqlmetal generated entity types containing StartsWith method:

public class EntityBase { }

public class Customer : EntityBase {

public string Name { get; set; }

public static IQueryable<Customer> StartsWith() {
Northwind db = new Northwind(connStr);
var q = from c in db.Customers
where c.Name.StartsWith("A%")
select c;
return q;
}}


public class Supplier : EntityBase {

public string Name { get; set; }

public static IQueryable<Supplier> StartsWith() {
Northwind db = new Northwind(connStr);
var q = from c in db.Suppliers
where c.Name.StartsWith("B%")
select c;
return q;
}}


I want to create single wrapper method for them with signature

EntityBase[] StartsWith( string lookupEntityTypeName )


I can use

static class EntityManager {

static EntityBase[] StartsWith( string lookupEntityTypeName ) {

switch (entityTypeName) {

case "Customer":
return Customer2.StartsWith().ToArray();

case "Supplier":
return Supplier.StartsWith().ToArray();
......
}
}
}

This switch statement requires hard coding of all entity type names.

How to replace this with general solution which does not require hard-coding
type names ?

Andrus.
 
M

Marc Gravell

Since the static method is on the entity itself, how about:

T[] StartsWith<T>() {
MethodInfo mi = typeof(T).GetMethod("StartsWith");
if(mi == null) throw new NotSupportedException();
return mi.Invoke();
}

Add in some casts, maybe some binding-flags, etc?

Marc
 
A

Andrus

Marc,
Since the static method is on the entity itself, how about:

T[] StartsWith<T>() {
MethodInfo mi = typeof(T).GetMethod("StartsWith");
if(mi == null) throw new NotSupportedException();
return mi.Invoke();
}

I tried

Type t = GetType("Customer2");

System.Reflection.MethodInfo mi = t.GetMethod("StartsWith");

if (mi == null) throw new NotSupportedException();

EntityBase[] result = (EntityBase[])mi.Invoke(null, null);


But got exception

System.InvalidCastException was unhandled
Message="Unable to cast object of type
'DBLinq.Linq.Table`1[Test_NUnit.ReadTest+Customer2]' to type
'EntityBase[]'."


This means that C# cannot cast IQueryable<Customer> to EntityBase[]

Andrus.
 
M

Marc Gravell

Ah right, I didn't see the IQueryable... but it shouldn't be hard to
get IQueryable into an array - even if you have to resort to raw
IEnumerable.

Personally, though, I'm not a big fan of methods that return radically
different data in this way... very hard to check at compile time...

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top