@David Thielen, Welcome to Microsoft Q&A, If you don't want queried spread all over my code, I recommend that you could create a class to include these methods.
Here is a code example you could refer to.
Model:
public class Student
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
}
public class StuContext:DbContext
{
public DbSet<Student> Students { get;set;}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string str = "connstr";
optionsBuilder.UseSqlServer(str);
}
}
EFHelper
public class EFHelper
{
public void Insert(StuContext context,Student student)
{
context.Students.Add(student));
context.SaveChanges() ;
}
public List<Student> GetById(StuContext context,int id)
{
var result=from m in context.Students where m.Id == id
select m ;
return result.ToList() ;
}
public void DeleteById(StuContext context, int id)
{
var result = from m in context.Students
where m.Id == id
select m;
context.Students.RemoveRange(result) ;
context.SaveChanges();
}
public void UpdateById(StuContext context, int id,string name)
{
var result = from m in context.Students
where m.Id == id
select m;
foreach (var item in result)
{
item.Name = name;
}
context.SaveChanges();
}
}
You could try to use the above EFHelper class to do the CRUD operations in ef core. However, I find that it may be a flaw that you need to define a very large number of overloaded functions if you need to delete, update or modify according to different conditions.
Hope my answer could help you.
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.