0

我在 Windows 窗体应用程序上使用的数据库有很多表,这些表由主键 int 标识字段、varchar 描述以及与另一个使用其 id 和描述的表的一对一关系组成。

我使用 Entity Framework Code First 映射到数据库的 C# POCO 的一个示例是:

public class OtherClass
{
  public int Id { get; set; }
  public string Description { get; set; }
}

public class Foo
{
  public int Id { get; set; }
  public string Description { get; set; }
  public OtherClass OtherClassProperty { get; set; }
}

因为像“Foo”这样的类都共享相同的结构,所以我正在创建一种基本形式,它应该能够与像这样的所有类一起使用。

我的问题是所有这些类的 ID 和描述都有不同的属性名称(例如,有时称为名称)。更不用说他们引用的另一个类总是不同的。

我的第一个想法是创建一个需要实现具有固定名称的属性的接口:Id、Description、KeyId、KeyDescription。这些属性将在每个类上实现,但仅指向“真实属性”。像这样:

public class Foo : MyInterface
{
  public int Id { get; set; }
  public string Description { get; set; }
  public OtherClass OtherClassProperty { get; set; }  

  //Interface implementation
  public int CommonId { get { return this.Id; } set { this.Id = value; } }
  public int CommonDescription { get { return this.Description; } set { this.Description = value; } }
  public int CommonKeyId { get { return this.OtherClassProperty.Id; } set { this.OtherClassProperty.Id = value; } }
  public int CommonKeyDescription { get { return this.OtherClassProperty.Description; } set { this.OtherClassProperty.Description = value; } }
}

我的印象是可能有更好的解决方案。我还可以想象实现属性属性并使用反射在运行时检查并获取属性。

有人对这种情况有什么建议吗?

提前致谢。

4

2 回答 2

1

对我来说,这看起来是一个很好的实现。

它直截了当且易于理解。

但是我会考虑使用显式接口实现

public int MyInterface.CommonId { get { return this.Id; } set { this.Id = value; } }

代替

public int CommonId { get { return this.Id; } set { this.Id = value; } }

如果可能的话,我还将创建一个长期的架构目标来重构数据库以统一命名。

于 2012-11-17T12:36:54.187 回答
1

固定名字听起来是个不错的方向。查看适配器模式以获得更正式的方法。

于 2012-11-17T12:40:41.763 回答