2016-03-05 127 views
0

我真的很抱歉這個愚蠢的問題,但我有一個問題,不知道,如何解決它。我有一個具有相同結構的幾個表的數據庫。 我在這個數據庫上使用了Entity Framework數據庫優先。現在我有幾個相同的實體。例如,實體框架相同的實體

public partial class Entity1 
    { 
     public int ID {get;set;} 
     public string Name {get;set;} 
     public bool Flag {get;set;} 
    } 

    public partial class Entity2 
    { 
     public int ID {get;set;} 
     public string Name {get;set;} 
     public bool Flag {get;set;} 
    } 

... 

我需要使用WCF來傳輸此實體。所以我創建一個像這個實體的數據合同。現在我想創建特定的更新方法,像波紋管:

public void update(EntityContract contract) 
{ 
    entity = //some method to get Entity from database by ID 
    bool needUpdate = false; 
    if(!contract.Name.Equals(entity.Name)) 
    { 
     entity.Name = contract.Name; 
     needUpdate = true; 
    } 
    ... use this codeblock for enother properties 
    if(needUpdate) 
    { 
     //update entity 
    } 
} 

有什麼方法來創建這個結構中所有實體的一種方法?

感謝您的任何建議。

回答

1

介紹的接口:

public interface ICommonEntity 
{ 
    int ID {get;set;} 
    string Name {get;set;} 
    bool Flag {get;set;} 
} 

它應用到你的實體:

public partial class Entity1 : ICommonEntity {} 
public partial class Entity2 : ICommonEntity {} 

讓你的 「某種方法從ID數據庫中獲取實體」 返回接口:

public ICommonEntity GetFromDatabase(...); 

然後,您只需要一種方法適用於所有實體類型。