简体   繁体   中英

Why is Entity Framework not generating proxy?

I have a DbContext with ProxyCreationEnabled set to true (actually it's the default value).

As far as I remember, this enables EF to load proxy entities from database, so any change we make to properties are recognized by the change tracker, and we can call SaveChanges() like this:

using (var db = new MyDbContext())
{
    var people = db.People.Where(p => p.Status = PersonStatus.New).ToList();
    foreach (var person in people)
    {
        person.Name = "Something";
    }
    db.SaveChanges();
}

The problem is: why would EF not use the proxy for a specific class, even though ProxyCreationEnabled is true? The class is not sealed, so it should be able to use proxy.

Here is my sample class:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime RegisterDate { get; set; }
    public PersonStatus Status { get; set; }
}

To generate proxy for property it should be virtual

public class Person
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual DateTime RegisterDate { get; set; }
    public virtual PersonStatus Status { get; set; }
}

To get change tracking proxies, the basic rule is that your class must be public, non-abstract or non-sealed. Your class must also implement public virtual getters/setters for all properties that are persisted. Finally, you must declare collection based relationship navigation properties as ICollection<T> only. They cannot be a concrete implementation or another interface that derives from ICollection<T> (a difference from the Deferred Loading proxy)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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