2012-07-24 76 views
1

我有三个结构相同的表。我正在使用实体框架。我想创建只接受三种类型的泛型函数。但我不能在类型参数中给出多个类型。有什么办法吗?或者我只想添加基类,如何创建基类,因为它们是从实体生成的?实体框架 - 如何为实体类创建基类?

回答

4

最简单的方法可能不是使用基类,而是使用接口。让我们假设共同财产是string Name,那么你可以做

interface IEntityWithName 
{ 
    string Name { get; set; } 
} 

// make sure this is in the same namespace and has the same name as the generated class 
partial class YourEntity1 : IEntityWithName 
{ 
} 

// ditto 
partial class YourEntity2 : IEntityWithName 
{ 
} 

public void DoSomething<T>(T entity) 
    // if you have no common base class 
    where entity : class, IEntityWithName 
    // or if you do have a common base class 
    where entity : EntityObject, IEntityWithName 
{ 
    MessageBox.Show(entity.Name); 
} 

究竟什么是可能取决于如何生成实体类,和你想在你的程序做什么。如果你不知道如何适应你的情况,你可以提供更多关于你想要做什么的信息吗?

+0

它工作正常。谢谢。我想发送一个类对象列表。怎么做? – user1548293 2012-07-24 12:05:27

+0

如果你的对象都有相同的类型,你可以使用'public void DoSomething (List entities)where ...',否则你可以使用'public void DoSomething(List entities)' – hvd 2012-07-24 12:24:19

+0

Thanks !. 。 有用。 – user1548293 2012-07-24 13:18:01