Preface

Masa Provides the basis for EntityFramework Data integration for , It also provides the functions of data filtering and soft deletion , Now we will introduce how to use it ?

MasaDbContext introduction

  1. newly build ASP.NET Core Empty item Assignment.MasaEntityFramework, And install Masa.Contrib.Data.EntityFrameworkCoreSwashbuckle.AspNetCoreMicrosoft.EntityFrameworkCore.InMemoryMicrosoft.EntityFrameworkCore.Tools

    dotnet add package Masa.Contrib.Data.EntityFrameworkCore --version 0.4.0-rc.4
    dotnet add package Swashbuckle.AspNetCore --version 6.2.3
    dotnet add package Microsoft.EntityFrameworkCore.InMemory --version 6.0.5
    dotnet add package Microsoft.EntityFrameworkCore.Tools --version 6.0.5

    install Swashbuckle.AspNetCore For the convenience of passing Swagger To operate the service

    install Microsoft.EntityFrameworkCore.InMemory It's for convenience , So use an in memory database , If you need to use other databases , Please install the corresponding package by yourself

    install Microsoft.EntityFrameworkCore.Tools To use CodeFirst Create database

  2. The new class User

    public class User
    {
    public int Id { get; set; } public string Name { get; set; } public uint Gender { get; set; } public DateTime BirthDay { get; set; } public DateTime CreationTime { get; set; } public User()
    {
    this.CreationTime = DateTime.Now;
    }
    }
  3. New user context UserDbContext.cs

    public class UserDbContext : MasaDbContext
    {
    public DbSet<User> User { get; set; } public UserDbContext(MasaDbContextOptions options) : base(options)
    {
    }
    }

    UserDbContext Instead of inheritance MasaDbContext, And add a parameter constructor , Parameter type is MasaDbContextOptions

    When there are multiple DbContext when , It needs to be inherited MasaDbContext<TDbContext>, The constructor parameter type is changed to MasaDbContext<TDbContext>

  4. The new class AddUserRequest As a parameter for adding users

    public class AddUserRequest
    {
    public string Name { get; set; } public uint Gender { get; set; } public DateTime BirthDay { get; set; }
    }
  5. The new class HostExtensions For migrating databases ( Use CodeFirst)

    public static class HostExtensions
    {
    public static void MigrateDbContext<TContext>(
    this IHost host, Action<TContext, IServiceProvider> seeder) where TContext : DbContext
    {
    using (var scope = host.Services.CreateScope())
    {
    var services = scope.ServiceProvider;
    var context = services.GetRequiredService<TContext>();
    context.Database.EnsureCreated();
    seeder(context, services);
    }
    }
    }
  6. modify Program.cs, newly added Swagger Support

    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen(); var app = builder.Build(); app.UseSwagger();
    app.UseSwaggerUI();

Unwanted Swagger Don't add , Use Swagger Just to test and invoke the service , Use Postman Or something else Http Tools can also

  1. modify Program.cs, Add user context ( a key )

    builder.Services.AddMasaDbContext<UserDbContext>(options =>
    {
    options.Builder = (_, dbContextOptionsBuilder) => dbContextOptionsBuilder.UseInMemoryDatabase("test")
    });
  2. modify Program.cs, Make the project support CodeFirst

    app.MigrateDbContext<UserDbContext>((context, services) =>
    {
    });

    Unwanted CodeFirst, Code generation is not supported, and the database cannot be added

  3. test MasaDbContext, modify Program.cs

    app.MapPost("/add", (UserDbContext dbContext, [FromBody] AddUserRequest request) =>
    {
    dbContext.Set<User>().Add(new User()
    {
    Name = request.Name,
    Gender = request.Gender,
    BirthDay = request.BirthDay
    });
    dbContext.SaveChanges();
    }); app.MapGet("/list", (UserDbContext dbContext) =>
    {
    return dbContext.Set<User>().ToList();
    });

    Run the project by yourself , perform add Then create a new user , After performing list Get more than one user data , Then prove MasaDbContext Correct use

How to use soft delete

  1. Choose Assignment.MasaEntityFramework And install Masa.Contrib.Data.Contracts.EF

    dotnet add package Masa.Contrib.Data.Contracts.EF --version 0.4.0-rc.4
  2. Modify the class User, And implement ISoftDelete, Change the code to :

    public class User : ISoftDelete// a key : Change to implementation ISoftDelete
    {
    public int Id { get; set; } public string Name { get; set; } public uint Gender { get; set; } public DateTime BirthDay { get; set; } public DateTime CreationTime { get; set; } public bool IsDeleted { get; private set; } public User()
    {
    this.CreationTime = DateTime.Now;
    }
    }

    Increase implementation ISoftDelete, And for IsDeleted Attribute addition set Support ( It can be private set;)

  3. modify Program.cs, And enable data filtering

    builder.Services.AddMasaDbContext<UserDbContext>(options =>
    {
    options.Builder = (_, dbContextOptionsBuilder) => dbContextOptionsBuilder.UseInMemoryDatabase("test");
    options.UseFilter();// Enable data filtering , Complete writing :options.UseFilter(filterOptions => filterOptions.EnableSoftDelete = true);
    });
  4. Test whether the soft deletion is successful

  • modify Program.cs, Add delete method

    app.MapDelete("/delete", (UserDbContext dbContext, int id) =>
    {
    var user = dbContext.Set<User>().First(u => u.Id == id);
    dbContext.Set<User>().Remove(user);
    dbContext.SaveChanges();
    });

Last , First call add Method after creating the user , Call later list Method to get the list of all users , And take out any one id Information , Then call delete Method to delete the user , Last call list Method , View removed id Whether there is , To verify whether the soft deletion is effective .

How to temporarily disable soft deletion filtering

In the default query, the data marked with deleted tags will be filtered and no longer be queried , But there are also some scenarios that need to query all the data , At this point, you need to use data filtering IDataFilter

  1. newly added All Method is used to query all data ( Contains data marked as deleted )

    app.MapGet("/all", (UserDbContext dbContext, [FromServices] IDataFilter dataFilter) =>
    {
    // adopt DI Get IDataFilter, And call it Disable Method can be temporarily disabled ISoftDelete filter
    using (dataFilter.Disable<ISoftDelete>())
    {
    return dbContext.Set<User>().ToList();
    }
    });
  2. Rerun the project , Repeat the steps of verifying soft deletion , Make sure to pass list Method cannot access data

    The reason for repeating the verify soft delete step is that this example uses an in memory database , After the project stops , All data will be cleared , Re execution is to ensure that the data exists , Only marked for deletion

  3. perform all Method , Get all the data , see id Whether the corresponding user data exists

Get the database connection string from the configuration file

  1. Selected items Assignment.MasaEntityFramework, And install Masa.Contrib.Data.EntityFrameworkCore.InMemory

    dotnet add package Masa.Contrib.Data.EntityFrameworkCore.InMemory --version 0.4.0-rc.4

    Install the corresponding database package as needed , Such as :Masa.Contrib.Data.EntityFrameworkCore.SqlServer (SqlServer)、Masa.Contrib.Data.EntityFrameworkCore.Pomelo.MySql (Pomelo Provided MySql)、Masa.Contrib.Data.EntityFrameworkCore.Oracle (Oracle) etc.

  2. modify Program.cs, Adjust the configuration of adding user context to :

    builder.Services.AddMasaDbContext<UserDbContext>(options => options.UseInMemoryDatabase().UseFilter());
  3. modify appsettings.json, Add user database connection string :

    {
    "ConnectionStrings": {
    "DefaultConnection": "test"// Replace with the specified database connection string
    }
    }
  4. modify Program.cs, newly added database Method , Verify that the current database is test

    app.MapGet("/database", (UserDbContext dbContext) =>
    {
    var field = typeof(MasaDbContext).GetField("Options", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic)!;
    var masaDbContextOptions = field.GetValue(dbContext) as MasaDbContextOptions;
    foreach (var dbContextOptionsExtension in masaDbContextOptions!.Extensions)
    {
    if (dbContextOptionsExtension is InMemoryOptionsExtension memoryOptionsExtension)
    {
    return memoryOptionsExtension.StoreName;
    }
    } return "";
    });

Last visit http://localhost:5002/database, Verify whether the current database name is consistent with the modified database name

common problem

  • How to change the default read configuration node ?
  1. Modify user context UserDbContext And increase ConnectionStringName characteristic :

    [ConnectionStringName("User")]// Custom node name 
    public class UserDbContext : MasaDbContext
    {
    public DbSet<User> User { get; set; } public UserDbContext(MasaDbContextOptions options) : base(options)
    {
    }
    }
  2. Modify the configuration appsettings.json

    {
    "ConnectionStrings": {
    "User": "test"// Instead of from User The node reads the database connection string
    }
    }
  • In addition to getting from the configuration file , Does it also support getting database connection strings from other places ?

There are currently two ways to change the database connection string .

Method 1: modify Program.cs, And delete appsettings.json Configuration of database connection string

  1. modify Program.cs

    builder.Services.Configure<MasaDbConnectionOptions>(option =>
    {
    option.ConnectionStrings = new ConnectionStrings(new List<KeyValuePair<string, string>>()
    {
    new("User", "test2")// Where the key is the node name , And ConnectionStringName Characteristic Name Keep the values consistent , If not specified ConnectionStringName, It should be DefaultConnection, The value is the database connection string
    });
    });
  2. modify appsettings.json To configure

    //  "ConnectionStrings": {
    // "User": "test"
    // },
  3. call database Method , Verify whether the current database is test2

Method 2: rewrite IConnectionStringProvider and IDbConnectionStringProvider And add to DI in

  1. The new class CustomizeConnectionStringProvider

    public class CustomizeConnectionStringProvider : IConnectionStringProvider
    {
    public Task<string> GetConnectionStringAsync(string name = "DefaultConnection") => Task.FromResult (GetConnectionString(name)); public string GetConnectionString(string name = "DefaultConnection") => "test3";
    }
  2. The new class CustomizeDbConnectionStringProvider

    public class CustomizeDbConnectionStringProvider : IDbConnectionStringProvider
    {
    public List<MasaDbContextConfigurationOptions> DbContextOptionsList { get; } = new()
    {
    new MasaDbContextConfigurationOptions("test3")
    };
    }
  3. modify Program.cs

    builder.Services.AddSingleton<IConnectionStringProvider,CustomizeConnectionStringProvider>();
    builder.Services.AddSingleton<IDbConnectionStringProvider,CustomizeDbConnectionStringProvider>();
  4. call database Method , Verify whether the current database is test3

summary

This article mainly explains MasaDbContext Basic usage and soft deletion 、 How to use data filtering , In the next article, we will explain MasaDbContext How to realize soft deletion 、 Data filtered , And how to realize it when using the database without specifying the database link string mentioned in this article

Source code of this chapter

Assignment05

https://github.com/zhenlei520/MasaFramework.Practice

Open source address

MASA.BuildingBlocks:https://github.com/masastack/MASA.BuildingBlocks

MASA.Contrib:https://github.com/masastack/MASA.Contrib

MASA.Utils:https://github.com/masastack/MASA.Utils

MASA.EShop:https://github.com/masalabs/MASA.EShop

MASA.Blazor:https://github.com/BlazorComponent/MASA.Blazor

If you treat our MASA Framework Interested in , Whether it's code contribution 、 Use 、 carry Issue, Welcome to contact us

The data access - EntityFramework More articles on Integration

  1. Java Web Learning Series ——Maven Web Integrated use in projects Spring、MyBatis Realize to MySQL Data access

    This article is based on the previous one Java Web Learning Series ——Maven Web Integrated use in projects Spring On the basis of , Yes, before Maven Web Upgrade the project , Realize to MySQL Data access . Add dependency Jar package this ...

  2. ABP Translation of official documents 9.1 EntityFramework Integrate

    EntityFramework Integrate Nuget package DbContext Storage Default warehouse Custom warehousing Apply specific basic warehousing classes Custom warehousing example Warehousing best practices Business management data storage ABP have access to ORM frame , It's inside ...

  3. ABP file - EntityFramework Integrate

    Document directory Content of this section : Nuget package DbContext Storage Default warehouse Custom warehousing Specific storage base classes Custom warehousing example Warehousing best practices ABP You can use any ORM frame , It's built in EntityFrame( following ...

  4. ABP Theory learning is EntityFramework Integrate

    Return to the general catalog This directory Nuget package establish DbContext Storage Warehouse base class Realize warehousing Custom warehousing method Read other ABP You can use any ORM Framework work , And it's built in EntityFramework Integrate . This article ...

  5. stay ASP.NET Create data access and business logic layers in ( turn )

    .NET Framework 4 When in ASP.NET When dealing with data in , Benefit from using common software patterns . One pattern is to separate data access codes from business logic codes that control data access or provide other business rules . In this mode , Both layers are ...

  6. test ClownFish、CYQ、Entity Framework、Moon、MySoft、NHibernate、PDF、XCode Data access component performance

    Next up : Due to the feedback from many garden friends , Some components should not be absent . The test complexity is not enough . There is still a lack of fairness in the test . So consider in the next release , Make sure to test with higher complexity in a fairer way . At the same time, it will be divided into 2 Group test , pure SQL Components and pure O ...

  7. Yii Learning from (2)-- Data access object (DAO)

    Excerpt from Yii Official website :http://www.yiiframework.com/doc/guide/1.1/zh_cn/database.dao Yii Provides powerful database programming support .Yii Data access object (DAO) ...

  8. Data access layer DAL( Database access abstract class DataProvider)

    Exposure data access layer DAL, See what form your project data access layer uses , Data access performance comparison What kind of data access form is a very important part of software coding , A good form of data access can not only improve the efficiency of code execution , Ability to collaborate , More importantly, yes ...

  9. Data access mode Repository Pattern

    Data access mode Repository Pattern   The data access layer is nothing more than adding, deleting, modifying and querying data , Increased . Delete . We can abstract and write a public interface or abstract class to define these methods , And use a base class to implement these methods , In this way, the children derived from the base class ...

  10. Springboot The data access , awesome !

    Springboot Provides a very powerful integration of the data access section , Support mysql,oracle While waiting for the traditional database , Also support Redis,MongoDB And so on , Greatly simplified DAO Code for , In especial Spring ...

Random recommendation

  1. redux Introduction and introduction

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 20.0px Helvetica } p.p2 { margin: 0.0px 0.0px 0.0px 0. ...

  2. android How to use thread sleep events

    SystemClock.sleep( Time ); no need Thread.sleep() Why : Throw the exception , Occupancy resources

  3. @Resource and @Autowired The difference between

    @Resource Is equivalent to @Autowired, It's just @Autowired Press byType Automatic injection , and @Resource Press default byName It's just automatic injection [email protected] There are two attributes that are important , branch ...

  4. Learning notes TF056:TensorFlow MNIST, Data sets 、 classification 、 visualization

    MNIST(Mixed National Institute of Standards and Technology)http://yann.lecun.com/exdb/mnist/ , Entry level computers ...

  5. [ turn ]java Middle scope public private protected And the difference between not writing

    Before explaining these four keywords , I think it's just class Make a simple definition of the relationship between , For inheriting one's own class,base class It can be said that they are all their own children , And for those in the same directory as yourself classes, I think it's all my friends ...

  6. Loj 【CQOI 2006】 Simple questions ,mmp

    #10117. 「 A passbook 4.1 practice 2」 Simple questions     Title Description Title source :CQOI 2006 There is one  nnn  Array of elements , Each element is initially  000. Yes  mmm  Orders , Or let a continuous sequence number ...

  7. SQL Server Timing execution SQL Method of statement

    SQL SERVER Timing task , You can start it up . But for more intuitive control , Write a program directly , Execute your stored procedures regularly . 1. Set up “SQL Server agent ”(SQL Server Agent) The service starts with the system ...

  8. git Branch update code command

    First step : Check the status   git status The second step : Add all   git add --all The third step : Check the status again   git status Step four : Submit       git commit -m ' To prepare ...

  9. kafka Custom serializer

    <kafka Authoritative guide > Customer.java public class Customer { private int customId; private String custome ...

  10. ros combination catkin_make and qtcreator

    First of all ros Official website IDE A tutorial for : http://wiki.ros.org/IDEs#QtCreator 1.qtcreator install Download it from the official website .run file , https://info.qt.io/ ...