繁体   English   中英

实体框架-如何为实体类创建基类?

[英]Entity Framework - How to create base class for entity class?

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

最简单的方法可能是不使用基类,而是使用接口。 假设通用属性是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);
}

确切可行的方法取决于您的实体类的生成方式以及您要在过程中执行的操作。 如果您不知道如何使它适应您的情况,是否可以提供有关您要做什么的更多信息?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM