简体   繁体   English

如何使用Entity Framework将2个相关对象存储在不同的数据库中

[英]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. 我正在使用C#、. net 4.5,ASP.NET MVC 5和Entity Framework 6重做旧的应用程序。

Because this web app will be used at the same time the old app, it needs to share the same databases. 由于此Web应用程序将与旧应用程序同时使用,因此需要共享相同的数据库。

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. DB1中有一个表Persons ,而DB2中有表Groups

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: 和Groups类:

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 然后我为每个数据库创建2个上下文

<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: 我的第一个问题是我的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) (请记住,我是MVC和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 . 我们决定使用EF 6,并且需要一种将用户与应用程序中的对象相关联的方法,我们正在尝试在这里找到的解决方案。 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. 计划是创建一个公共同义词(在上面的示例中为db2),并使用该同义词在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. 关于该答案的评论似乎是肯定的,我们仍在努力,但是一旦启动并运行,我将更新此答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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