我試圖讓微小的helper方法用於簡化日常操作 但在樣本:C#泛型LINQ的搜索條件
public static int getEntityId<Type, Entity>(String name) where Entity: class
{
Type type = _db.GetTable<Entity>().SingleOrDefault(t => t.name == name);
return 0;
}
我遇到錯誤:
Error 1 'Entity' does not contain a definition for 'name' and no extension method 'name' accepting a first argument of type 'Entity' could be found (are you missing a using directive or an assembly reference?) c:\work\asutp_migration\asutp_migration\Program.cs 89 62 asutp_migration
其實,這是預計的錯誤,但如何解決這個問題? 所有使用此方法的表/類都具有「名稱」字段/屬性。
UPD 1: 根據建議我這樣做:
public partial class unit : IHasName
{
}
interface IHasName
{
string name { get; }
int id { get; }
}
public static int getEntityId<Type, Entity>(String name) where Entity: class, IHasName
{
Type type = _db.GetTable<Entity>().SingleOrDefault(t => t.name == name);
return (type == null) ? type.id : 0;
}
與代碼:
int i = getEntityId<unit>("м");
Console.WriteLine(i);
我得到異常:
Unhandled Exception: System.NotSupportedException: The mapping of interface member IHasName.name is not supported.
UPD 2: http://connect.microsoft.com/VisualStudio/feedback/details/344903/linq-to-sql-mapping-interface-member-not-supported-exception 我不敢相信。這與我的問題有關嗎?
UPD 3: 是啊,看來這是VS的問題:http://social.msdn.microsoft.com/Forums/en/linqtosql/thread/bc2fbbce-eb63-4735-9b2d-26b4ab8fe589
UPD 4:
public static int getEntityId<Type>(String name) where Type: class, IHasName
{
Type type = _db.GetTable<Type>().SingleOrDefault(t => t.name.Equals(name));
return (type != null) ? type.id : 0;
}
所以這是一個解決方案,謝謝大家:-)
有什麼你試圖用這個代碼實現的目標是什麼? – 2010-02-04 04:04:36
我試圖防止像這樣的方法重複http://pastie.org/808750 – zerkms 2010-02-04 04:06:44