2012-02-23 64 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 
    }