Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2017
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.46 KB | None | 0 0
  1. using Microsoft.EntityFrameworkCore;
  2. using System.Collections.Generic;
  3.  
  4. namespace Example
  5. {
  6.     /**
  7.      * DbContext classes provide implicit access to a database through the LINQ query syntax and the EntityFrameworkCore ORM.
  8.      */
  9.     public class ExampleDataProvider : DbContext
  10.     {
  11.         /**
  12.          * The schema is defined implicitly through the member variables of the DbContext.
  13.          * Each DbSet provides transparent access to a table in the database through LINQ.
  14.          * The schema is initialised automatically by the DbContext base class where necessary.
  15.          * The columns of each table are defined by the member variables of the POCOs each DbSet holds.
  16.          */
  17.         public DbSet<Blog> Blogs { get; set; }
  18.         public DbSet<Post> Posts { get; set; }
  19.  
  20.         private int NextBlogId {
  21.             get {
  22.                 // Defining a custom getter so that NextBlogId will increment every time it is accessed.
  23.                 return NextBlogId++;
  24.             }
  25.         } = 0; // No, this isn't C++, that doesn't make it abstract.
  26.                // This is essentially the same as setting NextBlogId to 0 in the initialiser list of the constructor.
  27.  
  28.         private int NextPostId {
  29.             get {
  30.                 return NextPostId++;
  31.             }
  32.         } = 0;
  33.  
  34.         /**
  35.          * This method can be overridden to configure the DbContext when it is constructed.
  36.          * By selecting options with the optionsBuilder we choose various parameters for our database,
  37.          * including what type of database it is. .NET Core 2.0 supports MSSQL, SQLite, and a pure in-memory database.
  38.          * Note that no matter what database provider we choose, the query syntax is still the same.
  39.          * This means that when Microsoft finally get around to implementing NoSQL databse providers,
  40.          * a DbContext can be configured to use them by changing only a single line of code.
  41.          */
  42.         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  43.         {
  44.             // The database file will automatically be created
  45.             // and initialised with the schema defined above
  46.             // if it does not already exist.
  47.             optionsBuilder.UseSqlite("Data Source=ExampleDatabase.db");
  48.         }
  49.  
  50.         /**
  51.          * This method performs operations on our database.
  52.          * Methods like these can be consumed by a Controller class to implement a WebAPI,
  53.          * although obviously methods in a real DbContext would strive to be more generically useful.
  54.          */
  55.         void AddBlog(String blogUrl)
  56.         {
  57.             // We write to the database by using the LINQ methods and POCOs.
  58.             // POCOs can be specified with similar syntax to JSON objects.
  59.             Blogs.Add(new Blog {
  60.                 BlogId = NextBlogId,
  61.                 Url = blogUrl
  62.             });
  63.  
  64.             // All LINQ operations involving write operations are implicitly transactional.
  65.             // The transaction begins with the first write call and and doesn't finalise
  66.             // until we call SaveChanges(). This means that methods on DbContexts are thread
  67.             // safe, so we can use them asynchronously with Tasks and 'await'.
  68.             SaveChanges();
  69.         }
  70.  
  71.         void AddPost(String title, String content, String postUrl)
  72.         {
  73.             Blog authorBlog = Blogs
  74.                 .Where(b => postUrl.startsWith(b.Url))
  75.                 .GetFirstOrDefaultAsync();
  76.  
  77.             var newPost = new Post{
  78.                 PostId = NextPostId,
  79.                 Title = title,
  80.                 Content = content,
  81.                 BlogId = authorBlog.BlogId
  82.             };
  83.  
  84.             Posts.Add(newPost);
  85.  
  86.             // Yes, this actually updates authorBlog in the database!
  87.             authorBlog.Posts.Add(newPost);
  88.  
  89.             SaveChanges();
  90.         }
  91.     }
  92.  
  93.     /**
  94.      * These are POCOs (Plain Ole C# Objects).
  95.      * POCOs are C# classes consisting entirely of public member variables with automatic
  96.      * getters and setters.
  97.      * They form the in-code representation of the rows in our database.
  98.      *
  99.      * Rows can be retrieved from the database by using LINQ queries on DbSets of POCOs,
  100.      * or inserted into the database by constructing a POCO and adding it to the DbSet.
  101.      *
  102.      * POCOs can be implicitly serialised to JSON and sent as the response to GET requests
  103.      * using JSON WebAPI Controllers. They just need to be wrapped in an ObjectResult object.
  104.      */
  105.     public class Blog
  106.     {
  107.         /**
  108.          * Optionally, JSON.NET attributes can be added to the members of a POCO to change how it
  109.          * is serialised. The property below ensures that BlogId will always be the first member
  110.          * of the serialised object.
  111.          *
  112.          * Properties can also be used to change the names of members as they appear in JSON,
  113.          * specify if fields are optional or required, and specify what to write to the JSON
  114.          * if an optional field is null.
  115.          */
  116.         [JsonProperty(Order = -2)]
  117.         public int BlogId { get; set; }
  118.        
  119.         public string Url { get; set; }
  120.        
  121.         public int Rating { get; set; }
  122.        
  123.         public List<Post> Posts { get; set; }
  124.     }
  125.  
  126.     public class Post
  127.     {
  128.         public int PostId { get; set; }
  129.         public string Title { get; set; }
  130.         public string Content { get; set; }
  131.  
  132.         public int BlogId { get; set; }
  133.     }
  134. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement