I haven't updated my blog for a while. It's raining outside today and no one has made a reservation. I plan to sort out my recent experience of using Entity Framework DBContext. I've simply checked it online earlier. There is no similar knowledge sorting article for the latest version of EF. I hope it will be helpful to everyone.
1. Don't have Code first, and don't have DB first
Why do I hate Code first and DB first? First, Code first writes the code first. The database is completely generated by code, and the development stage is still acceptable. Once it reaches the product release stage, if we need to add fields, we can't use visual studio to update the database in the production environment. It sounds terrible. And another problem is that the generated database scripts are uncontrollable, so it is better to design them in advance. DB first is not much better. The reverse-turned code contains many useless files, and the database update also requires the Model generation process to be re-interpreted. It is impossible to understand why such a design is there. After saying so much, how can I solve it?
The database and domain model are designed separately, and the fields are mapped according to the corresponding relationship and customized link strings are used. They neither use the domain model to generate the database nor the database to generate the domain model. The example code is as follows. SQL Code takes the Destinations and TTable tables as examples:
CREATE TABLE [DBO].[Destinations] ( [DestinationId] [int] PRIMARY KEY NOT NULL, [Name] [nvarchar](max) NULL, [Country] [nvarchar](max) NULL, [Description] [nvarchar](max) NULL, [Photo] [varbinary](max) NULL
CREATE TABLE [TTT].[TTable] ( [Id] [int] PRIMARY KEY NOT NULL, [Name] [nvarchar](max) NULL )
Model Class:
using System; using ; using ; using ; using ; namespace Model { public class Destination { public int DestinationId { get; set; } public string Name { get; set; } public string Country { get; set; } public string Description { get; set; } public byte[] Photo { get; set; } public List<Lodging> Lodgings { get; set; } } public class Lodging { public int LodgingId { get; set; } public string Name { get; set; } public string Owner { get; set; } public bool IsResort { get; set; } public Destination Destination { get; set; } } public class TTable { public int Id { get; set; } public string Name { get; set; } } }
Connect String:
<connectionStrings> <add name="BAContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=;Integrated Security=SSPI;" providerName="" /> </connectionStrings>
DB Context:
using ; using ; using Model; namespace DataAccess { public class TTableConfiguration : EntityTypeConfiguration<TTable> { public TTableConfiguration() { ("TTable", "TTT"); } } public class BreakAwayContext : DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { (new TTableConfiguration()); } public BreakAwayContext(string connString) : base(connString) { } public DbSet<Destination> Destinations { get; set; } public DbSet<Lodging> Lodgings { get; set; } public DbSet<TTable> TTables { get; set; } } }
2. What should I do if the fields of the database table do not correspond to the fields of the domain model? For example, the TTable table in this article is under TTT Schema, while other representations are designed under DBO, the most convenient way is to use the fluent API. For the specific code, please refer to the TTableConfiguration Class and OnModelCreating() method. The configurable granularity is very fine, such as the domain model and which table corresponds to which column of which Schema in the database. This article configures the database table of the TTable class as the TTable table under TTT Schema.
public class TTableConfiguration : EntityTypeConfiguration<TTable> { public TTableConfiguration() { ("TTable", "TTT"); } }
3. Add and delete the search for things to support, the specific code is as follows.
public static int Insert() { var destination = new Destination { Country = "Chs", Description = "Chs is the language package", Name = "xsss" }; using (var context = new BreakAwayContext(["BAContext"].ConnectionString)) { var rt = (destination); (); return ; } } public static void Update(Destination destIn) { using (var context = new BreakAwayContext(["BAContext"].ConnectionString)) { var dest = (a => == ).Single(); = ; (); } } public static void Delete(int destId) { using (var context = new BreakAwayContext(["BAContext"].ConnectionString)) { var destination = new Destination() { DestinationId = destId }; (destination); (destination); (); } } public static Destination Query(int destId) { using (var context = new BreakAwayContext(["BAContext"].ConnectionString)) { IQueryable<Destination> dest = (a => == destId); return (); } }
4. If multiple operations are required to succeed or fail at the same time, the transaction needs to be manually started. The specific code is as follows.
public static void TransactionOps() { using (var context = new BreakAwayContext(["BAContext"].ConnectionString)) { using (var dbContextTransaction = ()) { try { var destination = new Destination { Country = "Chs", Description = "Chs is the language package", Name = "xs2s" }; var destId = (destination); (); (destId); (destId); (); (); } catch ( ex) { (); (()); } } } }
5. Pagination query is a common function of website design. A simple true pagination query method is as follows.
public static List<Destination> QueryPaging<TKey>(int pageIndex, int pageSize, Expression<Func<Destination, bool>> whereLambda, Expression<Func<Destination, TKey>> orderBy) { using (var context = new BreakAwayContext(["BAContext"].ConnectionString)) { return (whereLambda).OrderBy(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } }
Summarize
This article provides a detailed explanation of the latest version of Entity Framework for addition, deletion, modification and search operations, and provides a complete solution for separate design of database and domain model code. It also introduces common functions such as manual database tables and domain model mapping, database transaction implementation, and pagination query. I hope it will be helpful to everyone.
The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the relevant links below