实体框架相同的实体
本文关键字:实体 框架 | 更新日期: 2023-09-27 18:37:25
我真的很抱歉这个愚蠢的问题,但我有一个问题,不知道如何解决它。我有一个数据库,其中包含几个结构相同的表。我在此数据库上首先使用了实体框架数据库。现在我有几个相同的实体。例如
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
}
}
有没有办法为所有具有此结构的实体创建一个方法?
感谢您的任何建议。
引入一个接口:
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(...);
然后,对于所有实体类型,只需要一种方法。