Eza*_*zak 3 fluent entity-framework-core asp.net-core
我有两个已经存在的表(没有外键):
客户 (Id, Name, .....) 项目 (Id, CustomerId, name)
在我的 asp.net 核心应用程序中,我有两个模型:
public class Customer {
public int Id { get; set; };
public String Name { get; set; };
}
public class Project {
public int Id { get; set; };
public Customer Customer{ get; set; };
public String Name{ get; set; };
}
Run Code Online (Sandbox Code Playgroud)
以及用于此的数据上下文类
public class CustomerContext: DbContext
{
public CustomerContext(DbContextOptions<CustomerContext> options) : base(options)
{
}
public DbSet<CustomerContext> Customer { get; set; }
}
public class ProjectContext: DbContext
{
public ProjectContext(DbContextOptions<ProjectContext> options) : base(options)
{
}
public DbSet<ProjectContext> Project{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但我无法找到如何通过 customerId 获取 Projectclass 中的 Customer 对象
有人能帮助我吗?谢谢
编辑:现在我像下面的答案一样更改我的模型类
但是在加载页面时出现 SQL 异常 SqlException: Invalid object name 'Customer'。
projectList = await (from project in _context.Project
join customer in _customerContext.Customer on project.CustomerId equals customer.Id into tmp
from m in tmp.DefaultIfEmpty()
select new Project
{
Id = sollIst.Id,
CustomerId = sollIst.CustomerId,
Customer = m,
Name = sollIst.Name,
}
).ToListAsync();
Run Code Online (Sandbox Code Playgroud)
更新您的模型类,如下所示:
public class Customer {
public int Id { get; set; };
public String Name { get; set; };
}
public class Project {
public int Id { get; set; };
public String Name{ get; set; };
public int CustomerID { get; set; }
[ForeignKey("CustomerID")]
public Customer Customer{ get; set; };
}
Run Code Online (Sandbox Code Playgroud)
将两个 DbContext 合并为一个。
public class ProjectContext: DbContext
{
public ProjectContext(DbContextOptions<ProjectContext> options) : base(options)
{
}
public DbSet<Project> Projects { get; set; }
public DbSet<Customer> Customers { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后执行
projectList = await (from project in _context.Project
join customer in _context.Customer on project.CustomerId equals customer.Id into tmp
from m in tmp.DefaultIfEmpty()
select new Project
{
Id = sollIst.Id,
CustomerId = sollIst.CustomerId,
Customer = m,
Name = sollIst.Name,
}
).ToListAsync();
Run Code Online (Sandbox Code Playgroud)
我希望以下链接能帮助您了解如何跨不同数据库连接两个表。
| 归档时间: |
|
| 查看次数: |
8927 次 |
| 最近记录: |