我有一些由实体框架创建和维护的类。这些类代表我的数据库中的表。在其中两个表中,我有非常相似的字段。例如(伪对象):
public class RandomObject1
{
int Identifier { get; set; }
int ObjectType { get; set; }
int SourceID { get; set; }
string OriginationPont { get; set; }
string PhoneNumber { get; set; }
decimal Cost { get; set; }
int OtherThing1 { get; set; }
int OtherThing2 { get; set; }
int OtherThing3 { get; set; }
}
public class RandomObject2
{
int Identifier { get; set; }
int ObjectType { get; set; }
int SourceID { get; set; }
string OriginationPont { get; set; }
string PhoneNumber { get; set; }
decimal Cost { get; set; }
double CashValue1 { get; set; }
decimal Snowman2 { get; set; }
int BigFurryTree3 { get; set; }
}
请注意,这两个对象的前几个字段是相同的,填充这些字段的过程也相同。通常在这些情况下,我会有一个接口来声明前几个字段,以便我可以将此对象作为接口传递给各种进程。
但是,在这种情况下,我不控制构建这些类的代码,并且真的不希望每次重新生成时都必须从实体框架中编辑生成的 .cs 文件。
我想知道我是否缺少使用泛型来执行以下操作的巧妙方法:
// This method will populate SourceID, OriginationPoint, PhoneNumber and Cost
public void GenerateOriginationInformation<T>(ValidationInformation info, T objectToManipulate) where T : RandomObject1 || RandomObject2
{
objectToManipulate.SourceID = GenerateSourceID(info);
objectToManipulate.OriginationPoint = GenerateOriginationPoint(info);
objectToManipulate.PhoneNumber = FindPhoneNumberByOrigination(info);
objectToManipulate.Cost = DetermineCostBySourceAndOrigination(info);
}
现在,我必须构建一个完整的对象/层来填充并返回正确的对象,但导致我为这些事情做了两次大部分代码!
public void GenerateOriginationInformation(ValidationInformation into, RandomObject1 objectToManipulate)
{
objectToManipulate.SourceID = GenerateSourceID(info);
objectToManipulate.OriginationPoint = GenerateOriginationPoint(info);
objectToManipulate.PhoneNumber = FindPhoneNumberByOrigination(info);
objectToManipulate.Cost = DetermineCostBySourceAndOrigination(info);
}
public void GenerateOriginationInformation(ValidationInformation into, RandomObject2 objectToManipulate)
{
objectToManipulate.SourceID = GenerateSourceID(info);
objectToManipulate.OriginationPoint = GenerateOriginationPoint(info);
objectToManipulate.PhoneNumber = FindPhoneNumberByOrigination(info);
objectToManipulate.Cost = DetermineCostBySourceAndOrigination(info);
}
起初,这看起来还不错,但是为了解释和简洁起见,这段代码被高度简化了。由于我无法实现接口,是否有一种更简洁的方法可以使用泛型使这两种方法合二为一?
I don't control the code that builds these classes, and really don't want to have to edit the resulting .cs files from the Entity Framework every time it is regenerated
在评论中回答:“它是 EDMX”
从您的 EDMX 设计器生成的类默认是部分的(您不需要额外的工作),因此您可以在生成的文件旁边创建一个代码文件partial
,并在其中使类型实现接口。
生成类
public partial class RandomObject1
你的代码文件放在同一个项目中
public partial class RandomObject1 : ICommonInterface
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句