簡體   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