c# - 访问通用实例属性

标签 c# entity-framework generics

如何访问实例Id属性?我有以下代码:

public void InsertOrUpdate(Book book)
{
    if (book.Id == default(int)) {

现在我想让它通用:

public class TheRepository<T> : IRepository<T> where T : class
{
    public void InsertOrUpdate(T instance)
    {
        if (instance.Id == default(int))//How can I access Id here
        {
            context.Set<T>().Add(instance);

我搜索了类似的帖子,我认为我应该写类似 instance.GetType().GetProperty("Id").GetValue() 的内容,但我不知 Prop 体怎么做?

最佳答案

您可以像这样进行黑客攻击。定义一个接口(interface),它只有一个名为 Idint 类型的属性:

interface IHaveId
{
    public int Id { get; set; }
}

然后说明您的实体实现了该接口(interface):

public class Book : IHaveId

最后说明在您的通用 Repository 类中使​​用的类型应该实现此接口(interface)。

public class TheRepository<T> : IRepository<T> where T : class, IHaveId
{
    public void InsertOrUpdate(T instance)
    {
        if (instance.Id == default(int))
        {
            context.Set<T>().Add(instance);
        }
    }
}

这样做可以避免使用反射,一般来说这是非常昂贵的。此外,您的代码现在更加清晰。

关于c# - 访问通用实例属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43834764/

相关文章:

c# - asp.net mvc razor View 中的增量

mysql - 将 MySql Provider 与 Entity Framework 模型结合使用

c# - 在 Entity Framework Core 中包含集合

visual-studio - 在 azure 函数项目 Visual Studio 中添加 Entity Framework 作为 nuget 与手册

c# - 使用 C# Generics 进行界面设计

c# - 有没有办法在 .NET 中获取 flash 控件中的所有变量?

java - C# 相当于 Java 内存映射方法

c# - 如何将unicode字符串从c#传输到c/c++ dll

c# - 如何将匿名类型的 List 转换为 List<T>?

c# - 是否有任何令人信服的理由不能在 C# 中对默认值 (T) 使用等于运算符 (==)