c# - 如何匹配数据库中的表和模式名称?
问题描述
我在数据库中的表的名称是 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; }
}
}
解决方案
您可以添加一个Table属性来定义目标架构:
[Table("Company", Schema = "abc"]
public class Company
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CompanyId { get; set; }
推荐阅读
- django - 如何在django中上传图片
- c# - 为什么当表单失去焦点并重新获得焦点时,我的 FlowLayoutPanel 会自动滚动回顶部?
- java - 如果底层流是并行的,那么收集 java 流很重要
- ios - 无法将弱分配给自定义数组
- swift - 单元格未填充在表格内的第二个集合视图中
- manim - 如何在 Manim 中更改 TextMobject 的文本大小
- javascript - 如何使具有布尔值的状态属性出现在屏幕上(反应表单)
- javascript - 如何使用 Instafeed.js 2.0.0 按最喜欢的方式排序
- rust - 什么是 Rust 等价于 C++ 的虚拟覆盖以防止代码重写?
- c# - FluentValidation 自定义扩展方法,带有来自基本实体的参数