.net efcore 自定义sql

109 阅读1分钟

static void Main(string[] args)
{
    using (MyDBContext context = new MyDBContext())
    {
        Book book = new Book()
        {
            Title = "C# in Depth",
            PubTime = DateTime.Now,
            Price = 29.99,
            AuthorName = "Jon Skeet"
        };

        context.Books.Add(book);
        context.SaveChanges();

        Console.WriteLine("Book inserted successfully!");
    }
}

 static async System.Threading.Tasks.Task Main(string[] args)
        {
            using (MyDBContext context = new MyDBContext())
            {
                Book book = new Book()
                {
                    Title = "C# in Depth",
                    PubTime = DateTime.Now,
                    Price = 29.99,
                    AuthorName = "Jon Skeet"
                };

                // 使用插值语法生成 SQL 命令并执行
                int affectedRows = await context.Database.ExecuteSqlInterpolatedAsync(
                    $@"INSERT INTO T_Books (Title, PubTime, Price, AuthorName)
                       VALUES ({book.Title}, {book.PubTime}, {book.Price}, {book.AuthorName})");
                Console.WriteLine($"{affectedRows} row(s) affected!");
            }
        }