Created
July 14, 2019 15:19
-
-
Save chathuranga94/3cbc2d4b8f3c5ff2125f3f53c1edd9d4 to your computer and use it in GitHub Desktop.
efcore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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