我正在尝试使用微小的辅助方法来简化日常操作但是在样本上:
public static int getEntityId<Type, Entity>(String name) where Entity: class
{
Type type = _db.GetTable<Entity>().SingleOrDefault(t => t.name == name);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
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
Run Code Online (Sandbox Code Playgroud)
实际上,这是预期的错误,但如何解决这个问题呢?我将与此方法一起使用的所有表/类都具有"name"字段/属性.
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;
}
Run Code Online (Sandbox Code Playgroud)
并使用代码:
int i = getEntityId<unit>("?");
Console.WriteLine(i);
Run Code Online (Sandbox Code Playgroud)
我得到例外:
Unhandled Exception: System.NotSupportedException: The mapping of interface member IHasName.name is not supported.
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
所以这是一个解决方案,谢谢大家:-)
好吧,你需要制作一个通用约束来指定更具体的东西class.例如,如果您说where Entity : IHasName并IHasName定义了一个属性name,那么您将全部设置.
| 归档时间: |
|
| 查看次数: |
1923 次 |
| 最近记录: |