2012-02-23 67 views
0

我如何使用linq为具有不同命名法的表制作通用更新方法。 PS我只需要更新两个字段(浮两者),但他们的名字改变从一个表到另一个,并表的ID的名称也各不相同Linq通用方法

假设我有我的DataContext这些表:

Person {ID(key), Name, X(float), Y(float)} 
Vehicle {Code(key), Model, Latitude(float), Longitude(float)} 
Building {Name(key), Model, Latitude1(float), Longitude1(float)} 

* 表格是虚构的,但代表我的情况。我无法更改表格字段的名称,以实现标准命名法。 (我不制作数据库)。

我需要Linq中的通用方法。事情是这样的:

public void UdpateCoordinates(tableName, idOfTable, fieldLatitude, fieldLongitude) 
{ 
    //And make a Update here of the fields (fieldLatitude, fieldLongitude). 
    //Example person would be fields X and Y the ones to update. 
} 

在此先感谢

+4

也许你要问,而不是一个具体问题是“我需要....谢谢。” – ken2k 2012-02-23 10:47:17

+1

您可以修改表示实现通用接口的表的C#类吗? – dtb 2012-02-23 10:47:58

+0

我不能修改类,因为其他应用程序已经使用bd。谢谢。 – ramo2712 2012-02-23 10:51:47

回答

0

首先,你需要一个接口

public interface IPosition { 
    public int ID {get ;} 
    public Latitude {get; set;} 
    public Longitude {get; set;} 
} 

使类车辆,大楼实现的接口。

这里是UdpateCoordinates方法的可能版本:

public void UdpateCoordinates<T>(IEnumerable<T> table, int ID, float latitude, float longitude) where T: IPosition { 
     var entity = table.Where(x.ID == ID).FirstOrDefault(); 
     if (entity != null){ 
      entity.Latitude = longitude ; 
      entity.Longitude = longitude ; 
     } 

     //Save the entity here 
    }