首页 > 解决方案 > 如何匹配数据库中的表和模式名称?

问题描述

我在数据库中的表的名称是 abc.Company,其中 abc 是一个模式。如何创建模型类以使名称与数据库中的表名匹配?我已经完成了如下所示的操作,但它无法从数据库中返回任何记录。控制器从数据库中给出 0 条记录。

有任何想法吗?

公司控制器.cs

public ActionResult CompanyDetails()
{
    IList<AddCompanyViewModel> viewModels = new List<AddCompanyViewModel>();

    var companies = db.Companies.ToList<Company>();

    foreach (var company in companies)
    {
         viewModels.Add(new AddCompanyViewModel
         {
             CompanyId=company.CompanyId,
             CompanyCode = company.CompanyCode,
             CompanyName = company.CompanyName,
             IsCompanyActive = company.Active,
             CreatedOn = company.CreatedDate
         });
    }

    return View(viewModels);
}

实体模型类:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace MiJack.Web.ProjectAdmin.Entities
{
       
    public class Company
    {
       [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
       public int CompanyId { get; set; }
       public string CompanyCode { get; set; }
       public string CompanyName { get; set; }
       public bool Active { get; set; }
       public DateTime CreatedDate { get; set; }
    }
}

DataAccessLayer 类:

using MiJack.Web.ProjectAdmin.Entities;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace MiJack.Web.ProjectAdmin.DataAccessLayer
{
   public class ProjectAdminDAL:DbContext
   {
      public ProjectAdminDAL() : base("ProjectAdmin")
      {
  
      }
        private static IDictionary<string, string> entitySetNames { get; set; }
        public DbSet<Company> Companies { get; set; }

        
        static ProjectAdminDAL()
        {
            // A dictionary that stores a mapping between entity objects (e.g. Vehicle) and
            // DbSets (e.g. Vehicles).
            //
            // This allows us to have a single Add method in Repository.cs that adds entities
            // to the object context by the DbSet name
            // Format
            //
            // { Entity, DbSet }
            // e.g.
            // { "Lock", "Locks" }
            ProjectAdminDAL.entitySetNames = new Dictionary<string, string>{
                {"Company", "Companies"},
            };

        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }

        public System.Data.Entity.DbSet<MiJack.Web.ProjectAdmin.ViewModels.AddCompanyViewModel> 
        AddCompanyViewModels { get; set; }
    }
}

标签: c#databaseentity-framework

解决方案


您可以添加一个Table属性来定义目标架构:

[Table("Company", Schema = "abc"]
public class Company
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int CompanyId { get; set; } 


推荐阅读