实体框架相同的实体

时间:2016-03-05 11:25:43

标签: c# entity-framework wcf

我真的很抱歉这个愚蠢的问题,但我有一个问题,不知道,如何解决它。我有一个数据库,其中有几个具有相同结构的表。 我在这个数据库中首先使用了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来传输这些实体。所以我创建了一个像这个实体的数据交换。现在我想创建像bellow一样的特定更新方法:

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 个答案:

答案 0 :(得分: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(...);

然后,您只需要一种方法用于所有实体类型。