Question

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();
    }

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?

Was it helpful?

Solution

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

Should be:

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; }
}

EDIT:

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top