EntityFramework Core入门教程-04-插入数据

原文:https://blog.csdn.net/weixin_40719943/article/details/106959206


1、通过控制台将生成的SQL语句日志打印出来:

安装Microsoft.Extensions.Logging.Console组件:

image

在Demo.Data项目中,更改DbContext文件:

using Demo.Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace Demo.Data
{
    public class ContextDemo : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder
                .UseLoggerFactory(ConsolLoggerFactory)
                .UseSqlServer(@"Data Source=(localdb)V11.0;Initial Catalog=efcoreDemo;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //为GamePlayer设置联合主键
            modelBuilder.Entity<GamePlayer>().HasKey(x => new { x.PlayerId, x.GameId });
            //指定一对一关系
            modelBuilder.Entity<Resume>()
                .HasOne(x => x.Player)
                .WithOne(x => x.Resume)
                .HasForeignKey<Resume>(x => x.PlayerId);
        }

        public DbSet<League> Leagues { get; set; }
        public DbSet<Club> Clubs { get; set; }
        public DbSet<Player> Players { get; set; }

        public static readonly ILoggerFactory ConsolLoggerFactory =
            LoggerFactory.Create(builer =>
            {
                builer.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name
                && level == LogLevel.Information)
                .AddConsole();
            });
    }
}

在Demo.App项目中,修改Program.cs

using Demo.Data;
using Demo.Domain;
using System;

namespace Demo.App
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            using var context = new ContextDemo();//C#8语法,当前方法结束后释放资源

            //添加一条数据
            var league1 = new League
            {
                Name = "LeagueA"
            };
            context.Leagues.Add(league1);

            var count = context.SaveChanges();//返回修改的记录数
            Console.WriteLine(count);
        }
    }
}

运行Demo.App项目,可以看到控制台显示出了SQL语句。

image

2、插入数据的方案

通过实例化DbContext,对数据库进行插入,EFCore提供了四个接口插入:
context.Leagues.Add();
context.Leagues.AddRange();添加多个实体
context.Add();添加多种实体
context.AddRange();

调用Add和AddRange方法后并不会立即更新数据库,执行SaveChange()才会将数据插入到数据库中

using var context = new ContextDemo();//C#8语法,当前方法结束后释放资源

//添加一条数据
var league1 = new League
{
    Name = "LeagueA"
};
context.Leagues.Add(league1);

//AddRange添加多条数据
var LeagueList = new List<League>
{
    new League{Name="LeagueB"},
    new League{Country="Japan",Name="LeagueC"}
};
context.Leagues.AddRange(LeagueList);


var league2 = new League { Name = "leagueD", Country = "UK" };
var lealgue3 = new League { Name = "leagueE", Country = "Australia" };

var leagueA = context.Leagues.FirstOrDefault(e => e.Name == "LeaguA");
var club1 = new Club
{
    Name = "Club1",
    City = "Shanghai",
    DateOfEstablishment = new DateTime(1988, 12, 16),
    League = leagueA
};

var club2 = new Club
{
    Name = "Club2",
    City = "Shanghai",
    DateOfEstablishment = new DateTime(1988, 12, 16),
    League = leagueA,
    Players=new List<Player>
    {
        new Player{Name="Henry",DateOfBirth=new DateTime(1993,01,25) },
        new Player{Name="Jack",DateOfBirth=new DateTime(1991,01,25) }
    }
};
//添加不同类型的实体
context.AddRange(club1, league2, lealgue3, club2);

var count = context.SaveChanges();//返回修改的记录数
Console.WriteLine(count);

原文地址:https://www.cnblogs.com/springsnow/p/13403748.html