在Entity Framework中向部分类添加接口不起作用 [英] Adding interface to partial class in Entity Framework does not work

查看:52
本文介绍了在Entity Framework中向部分类添加接口不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的实体框架(v5)对象上使用了部分类(.NET 4.5).我向该部分类添加了一个接口,但是针对此接口测试EF对象为false,但是应该将其识别为该接口是在部分类上定义的.这是我正在尝试的:

I am using a partial class (.NET 4.5) on my Entity Framework (v5) object. I added an interface to this partial class, but testing the EF object against this interface is false, but it should be recognized as the interface is defined on the partial class. Here is what I am trying:

public interface Product : ILastModified
{
  public DateTime LastModified { get; set; }
}

然后在我的数据层中尝试此操作:

Then in my data layer I am trying this:

    public virtual int Update<T>(T TObject) where T : class
    {
        //WHY ALWAYS FALSE?
        if (TObject is ILastModified)
        {
          (TObject as ILastModified).LastModified = DateTime.Now;
        }

        var entry = dbContext.Entry(TObject);
        dbContext.Set<T>().Attach(TObject);
        entry.State = EntityState.Modified;
        return dbContext.SaveChanges();
    }

问题是,即使我在部分类上设置了如果(TObject为ILastModified)",它始终为false.我是在做错什么,还是有办法实现这样的目标?

The problem is that "if (TObject is ILastModified)" is always false even though I set it on the partial class. Am I doing something wrong or is there a way to achieve something like this?

推荐答案

您已将 Product 定义为接口而不是类.

You've defined your Product as an Interface instead of a Class.

应该是:

interface ILastModified {
{
    DateTime LastModified { get; set; }
}

public partial class Product : ILastModified
{
    /* this prop is declared in the Ef generated class   */
    //public DateTime LastModified { get; set; }
}

对于方法的更改,您不必使用:

You don't have to use Is with this change to your method:

public virtual int Update<T>(T TObject) where T : class, ILastModified
{
    TObject.LastModified = DateTime.Now

    var entry = dbContext.Entry(TObject);
    dbContext.Set<T>().Attach(TObject);
    entry.State = EntityState.Modified;
    return dbContext.SaveChanges();
}

这样,如果传递的类型未实现该接口,则会出现编译时错误.

and this way you'll get compile time errors if the type you pass does not implement the interface.

这篇关于在Entity Framework中向部分类添加接口不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆