我们有一个旧数据库,我们要求与该数据库进行只读交互以获取一些数据(我们无法更改其架构)。
有些表不是使用FK相互关联的,而是使用column的值,不幸的是,从属表上的Primary key和related column具有不同的数据类型(ex char和nvarchar)。
使用实体框架核心,我编写了一些映射,如下所示:
EntityTypeBuilder<Supplier>.HasMany(x => x.CatalogueItems)
.WithOne(x => x.Supplier)
.HasForeignKey(x => x.Vendor);
但是当我尝试使用 Include 方法来快速加载导航属性时:
dbContext.CatalogueItems.Include(x => x.Supplier).FirstOrDefault();
我将Supplier设置为null,当我使用投影将其写入时,我会获得Supplier数据:
dbContext.CatalogueItems.Select(x => new {
x.ItemCode,
x.Supplier
}).FirstOrDefault();
能否请您告诉我如何使用“包含”对它进行调整以获取导航属性?
编辑:
Startup.cs:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyDBContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
services.AddIdentityCore<User>()
.AddEntityFrameworkStores<MyDBContext>()
.AddDefaultTokenProviders();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// Add application services.
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
app.UseHttpsRedirection();
}
app.UseMvc();
}
}