Skip to content

Instantly share code, notes, and snippets.

@chathuranga94
Created July 14, 2019 15:19
Show Gist options
  • Save chathuranga94/3cbc2d4b8f3c5ff2125f3f53c1edd9d4 to your computer and use it in GitHub Desktop.
Save chathuranga94/3cbc2d4b8f3c5ff2125f3f53c1edd9d4 to your computer and use it in GitHub Desktop.
efcore
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
namespace efcore
{
public class AppDBContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=app.db");
}
}
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public ICollection<Course> Courses { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string Title { get; set; }
public int StudentId { get; set; }
public Student Student { get; set; }
}
}
using System;
namespace efcore
{
class Program
{
static void Main(string[] args)
{
using (var db = new AppDBContext())
{
Student student1 = new Student { StudentId = 1000, Name = "Hey name" };
db.Students.Add(student1);
var count = db.SaveChanges();
Console.WriteLine("{0} records saved to database", count);
Console.WriteLine();
Console.WriteLine("All students in database:");
foreach (var student in db.Students)
{
Console.WriteLine("Student ID-{0} Name-{1}", student.StudentId, student.Name);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment