如何使用Entity Framework在MVC中的两个上下文之间传递数据

时间:2018-02-04 00:06:25

标签: c# asp.net-mvc entity-framework

在我的带有Entity Framework的MVC应用程序中,我有2个上下文。一个是我的业务数据(DemoPoolEntities),另一个是ASPNet身份数据,如ASPNetUsers和ASPNetRoles(ApplicationDbCcontext)。数据全部存储在同一个数据库中。我将它们分别分别放在我的项目DemoPoolModels.csIdentityModels.cs中的两个不同模型中。

我需要将数据从ApplicationDbContext传递到我的DemoPoolEntities上下文,以便在我的一些视图中显示它们。

例如,我的数据库中有一个Customer对象。 Customer位于DemoPoolEntities上下文中,但与AspNetUser中的ApplicationDbContext具有外键关系。我需要在ASPNetUser控制器的Index视图中显示此Customer,这将显示客户所属的用户。

然而,当我进入视图时,我不断收到以下错误:

System.Data.Entity.Core.EntityCommandExecutionException: 'An error occurred while executing the command definition. See the inner exception for details.'

'Inner Exception
SqlException: Invalid column name 'AspNetUser_Id'.'

CustomerController.cs

// GET: Customers
        [Authorize(Roles = "Admin, User")]
        public ActionResult Index()
        {

            return View(db.Customers.ToList());
        }

客户视图(Index.cshtml)

@Html.DisplayFor(modelItem => item.UserId)

在我的客户模式中

[StringLength(128)]
        public string UserId { get; set; }

        public virtual ApplicationUser AspNetUser { get; set; }

IdentityModels.cs

namespace DemoPool.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DemoPoolEntities", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
}

DemoPoolModels.cs

public partial class DemoPoolEntities : DbContext
    {
        public DemoPoolEntities()
            : base("name=DemoPoolEntities")
        {
        }
public virtual DbSet<Customer> Customers { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
modelBuilder.Entity<Customer>()
                .Property(e => e.CompanyName)
                .IsUnicode(false);

            modelBuilder.Entity<Customer>()
                .Property(e => e.FirstName)
                .IsUnicode(false);

            modelBuilder.Entity<Customer>()
                .Property(e => e.LastName)
                .IsUnicode(false);

            modelBuilder.Entity<Customer>()
                .Property(e => e.PhoneNumber)
                .IsUnicode(false);

            modelBuilder.Entity<Customer>()
                .Property(e => e.Email)
                .IsUnicode(false);

            modelBuilder.Entity<Customer>()
                .Property(e => e.Address1)
                .IsUnicode(false);

            modelBuilder.Entity<Customer>()
                .Property(e => e.Address2)
                .IsUnicode(false);

            modelBuilder.Entity<Customer>()
                .Property(e => e.City)
                .IsUnicode(false);

            modelBuilder.Entity<Customer>()
                .Property(e => e.State)
                .IsUnicode(false);

            modelBuilder.Entity<Customer>()
                .Property(e => e.Zip)
                .IsUnicode(false);
modelBuilder.Entity<IdentityUserLogin>()
                .HasKey<string>(l => l.UserId);

            modelBuilder.Entity<IdentityRole>()
                .HasKey<string>(r => r.Id);

            modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
}

所以我的问题是,当ASPNetUser视图位于两个不同的上下文中时,如何获取Customer引用的Customer信息,并且我应该采用不同的方式这样做?

1 个答案:

答案 0 :(得分:0)

我通过为我尝试访问的EF对象创建模型来实现此目的。所以在这种情况下我为ASPNetUser创建了一个模型。这似乎有效。