is it possible to share POCO object between two Db

2019-08-29 00:04发布

问题:

I have some POCO classes which can generally divided into two groups, for example:

public class Student
{
    public Student()
    {
        this.Courses = new List<Course>();
        this.Clubs = new List<Club>();
    }

    public int Id { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
    public virtual ICollection<Club> Clubs { get; set; }
}

and corresponding Course and Club classes, and they all have their own relationships to other classes.

The problem is, those two groups are big, they both contains a lot of classes, and each of them is a working unit, like student courses management unit which will provide functions for anything related to course; and club management unit which will provide functions. So I am not planning to put them together into one DbContext.

There are some requirements that will need to get a student from club then retrieve its course information. What I am doing now, is do another query in course unit by using the student Id I got from club unit. Which works fine but I hopping to make it simpler, like

foreach(var student in club.Students){
    ClubContext.Detach(student);
    CourseContext.Attach(student);
    foreach(var c in student.Courses){
      ...
    }
}

but I got some exception like this:

There is already a generated proxy type for the object layer type 'POCOTest.Models.Student'. This occurs when the same object layer type is mapped by two or more different models in an AppDomain.

Is this possible? and if so, how? Thanks~

回答1:

You can have single class mapped in multiple contexts but the mapping should be always the same. If it is not the same you cannot use dynamic proxies (lazy loading) because each mapping demands its own proxy type handling its navigation properties.

In your case the first context mapping contains Student entity with relation to Club but this relation doesn't exist in the second mapping where in contrary relation with Course exists. That demands two different proxy types for the same entity type.

The exception says that it is not supported. There are two reasons why this cannot work:

  • EF stores proxy types in static dictionary where each entity type can have only single generated proxy
  • Even if you fix the first point (by downloading source codes and modifying them) you will still not be able to do what you want because proxy type is the entity. It is not a wrapper. So the type cannot be replaced when you detach it from the first context and attach to second one.


回答2:

If you don't need lazy loading, just remove the "virtual" keyword from your navigation properties and it will work as you want. Virtual is used to enable Lazy Loading.