Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created July 21, 2021 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/9ed0ca561879f3f40d93986247ba32c5 to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/9ed0ca561879f3f40d93986247ba32c5 to your computer and use it in GitHub Desktop.
.NET - Entity Framework Core - Map C# Method to SQL Function Demo
class Program
{
static async Task Main(string[] args)
{
// First Unit-of-Work showing Add operation
AddStudents();
// Second Unit-of-Work showing Update and Remove operations
await QueryStudents();
}
static void AddStudents()
{
using var context = BuildUniversityContext();
var studentCollection = new List<Student>()
{
new Student { FirstName = "John", LastName = "Doe", Address = "4 Privet Drive" },
new Student { FirstName = "Jane", LastName = "Doe", Address = "6 Privet Drive" },
new Student { FirstName = "Harry", LastName = "Potter", Address = "8 Privet Drive" },
new Student { FirstName = "Ginny", LastName = "Weasly", Address = "10 Privet Drive" },
};
context.AddRange(studentCollection);
context.SaveChanges();
}
static async Task QueryStudents()
{
using var context = BuildUniversityContext();
// Query using the method GetStudentsCountWithSameLastName
// Return only those records which surnames appear more than once
var studentsQuery = from student in context.Students
where context.GetStudentsCountWithSameLastName(student.LastName) > 1
select student;
// Get Results from Query
var studentsCollection = await studentsQuery.ToListAsync();
// Print Results
Console.WriteLine("---------------------------------------");
foreach(var student in studentsCollection)
{
Console.WriteLine(student);
}
Console.WriteLine("---------------------------------------");
}
static UniversityContext BuildUniversityContext()
{
var dbContextBuilder = new DbContextOptionsBuilder<UniversityContext>();
var connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=University; Integrated Security=True;";
dbContextBuilder.UseSqlServer(connectionString);
return new UniversityContext(dbContextBuilder.Options);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment