【问题标题】:Entity Framework same entities实体框架相同的实体
【发布时间】:2016-03-05 11:25:43
【问题描述】:

对于这个愚蠢的问题,我真的很抱歉,但我有一个问题,不知道如何解决。我有一个包含几个具有相同结构的表的数据库。 我在这个数据库上首先使用了实体框架数据库。现在我有几个相同的实体。例如,

    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
   }
}

有没有办法为所有具有这种结构的实体创建一个方法?

感谢您的建议。

【问题讨论】:

    标签: c# entity-framework wcf


    【解决方案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(...);
    

    那么你只需要一种方法来处理所有实体类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多