简体   繁体   中英

How to have 2 related objects stored in different databases using Entity Framework

I'm redoing an old application using C#, .net 4.5, ASP.NET MVC 5 and Entity Framework 6.

Because this web app will be used at the same time the old app, it needs to share the same databases.

To save me some time I've generated my model based on the existing databases. (to do this I first gathered all tables in the same database, defined their relationships, generated the model based on that new database with every table and then use the old databases to run my code)

在此处输入图片说明

To clarify my problem I created this simple example.

A person can belong to many groups.

One table Persons is in DB1 and the table Groups is in DB2.

The relation between these 2 tables doesn't exist because they are in different databases. But I should be able to know to which Groups a Person belongs to and which persons are in a given group.

The generated code for the class persons is:

public partial class Persons
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }

    [Required]
    [StringLength(50)]
    [Display(Name = "Person Name")]
    public string Name { get; set; }

    public int GroupID { get; set; }

    public virtual Groups Groups { get; set; }
}

and the Groups class:

public partial class Groups
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Groups()
    {
        Persons = new HashSet<Persons>();
    }

    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }

    [Required]
    [StringLength(50)]
    [Display(Name = "Group Name")]
    public string Name { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Persons> Persons { get; set; }
}

then I created 2 contexts one for each database

<add name="ModelContext1" connectionString="data source=PROG-PC\SQLEXPRESS;initial catalog=DB1;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
<add name="ModelContext2" connectionString="data source=PROG-PC\SQLEXPRESS;initial catalog=DB2;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />

and the respective context classes (I'm not sure if I should keep the code related to the foreign keysm since they dont actually exist)

public partial class ModelContext1 : DbContext
    {
        public ModelContext1()
            : base("name=ModelContext1")
        {
        }

    public virtual DbSet<Persons> Persons { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Groups>()
            .HasMany(e => e.Persons)
            .WithRequired(e => e.Groups)
            .HasForeignKey(e => e.GroupID)
            .WillCascadeOnDelete(false);
    }
}



public partial class ModelContext2 : DbContext
    {
        public ModelContext2()
            : base("name=ModelContext2")
        {
        }

    public virtual DbSet<Groups> Groups { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Groups>()
            .HasMany(e => e.Persons)
            .WithRequired(e => e.Groups)
            .HasForeignKey(e => e.GroupID)
            .WillCascadeOnDelete(false);
    }
}

My first problem is my PersonControler:

public class PersonsController : Controller
    {
    private ModelContext1 db = new ModelContext1();
    private ModelContext2 db2 = new ModelContext2();

    // GET: Persons
    public ActionResult Index()
    {
        var persons = db.Persons.Include(p => p.Groups);
        return View(persons.ToList());
    }

在此处输入图片说明

(keep im mind I'm new to MVC and EntityFramework)

How can I solve this problem?

What other considerations should I take?

I realize that it's a year later, but since I stumbled upon this maybe it will help someone else in a similar situation. We have a user/client database that stores our Identity data for user and client logins, roles, etc... We then have our application database that stores the actual application data. We offer our clients the ability to physically partition their data and as part of a system rewrite we're looking for ways to keep our sanity as our client base grows. We decided to use EF 6 and needed a way to relate users to objects in the application, we're trying the solution I found here . The plan is to create a public synonym (in db2 in the example above) and use that to create the relationships in the Context Configuration. Comments on that answer seem positive, we're still working on it but I'll update this answer once we're up and running.

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