[英]which is the correct way to insert data with subquery inside using ef core
I have a .net API using EF Core with the following entities following entities 我有一个使用EF Core的.net API,以下实体如下
My goal is to send an User
id
to the API and based on this id
the application should retrieve the name
from the User
table and insert it on the Name
table 我的目标是将
User
id
发送到API,并且基于此id
,应用程序应从User
表中检索name
并将其插入Name
表中
UserRepository.cs
public int GetNameById(int userId)
{
var result = _context.User.Where(u => u.Id == userId).Select(u => new { u.Name }).FirstOrDefault();
...
}
NameRepository.cs
public void AddName(Name name)
{
_context.Name.Add(name);
}
// _context.SaveChanges() later
In the controller is where I call their respective services and they call their respective repositories. 在控制器中,我分别调用各自的服务和各自的存储库。 I made the search and the insert separately so I can reuse these method in the future.
我分别进行了搜索和插入,因此将来可以重用这些方法。 EF core is generating two queries, I wanted it all in single one for performance reasons, how can I do it?
EF核心正在生成两个查询,出于性能原因,我希望将所有查询全部放在一个查询中,该怎么办? They already share the same context
他们已经共享了相同的上下文
In short I want methods that can be reusable and run all in one query. 简而言之,我想要可以重用并在一个查询中全部运行的方法。 (On my real project the entities are totally different, I changed it so it would be easier to understand my issue)
(在我的真实项目中,实体完全不同,我对其进行了更改,因此更容易理解我的问题)
1. method should return a string
value, not int
, i guess: 1.方法应该返回一个
string
值,而不是int
,我猜:
public string GetNameById(int id)
{
return dbContext.Users.FirstOrDefault(q => q.Id == id)?.Name;
}
according your model: 根据您的模型:
var name = new Name { Name = "New name" }; name.Id = 0;
if Name.Id is IDENTITY column, then comment Id assignment otherwise use some value ... 如果Name.Id是IDENTITY列,则注释ID分配,否则使用一些值...
public void AddName(Name name)
{
dbContext.Names.Add(name);
}
// dbContext.SaveChanges(); somewhere
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.