Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# orm框架

作者:花小泽ノ   发布日期:2026-01-03   浏览:71

using System;
using System.Data.Entity; // 引用 Entity Framework 的命名空间

namespace CSharpORMExample
{
    // 定义一个实体类,对应数据库中的表
    public class Product
    {
        public int Id { get; set; } // 主键
        public string Name { get; set; }
        public decimal Price { get; set; }
    }

    // 继承 DbContext 类来创建一个数据库上下文
    public class MyDbContext : DbContext
    {
        public DbSet<Product> Products { get; set; } // DbSet 代表数据库中的表
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new MyDbContext())
            {
                // 添加新记录
                var product = new Product { Name = "Laptop", Price = 999.99m };
                context.Products.Add(product);
                context.SaveChanges(); // 将更改保存到数据库

                // 查询所有产品
                var products = context.Products.ToList();
                foreach (var p in products)
                {
                    Console.WriteLine($"Id: {p.Id}, Name: {p.Name}, Price: {p.Price}");
                }

                // 更新记录
                var updateProduct = context.Products.Find(1); // 假设要更新 Id 为 1 的产品
                if (updateProduct != null)
                {
                    updateProduct.Price = 899.99m;
                    context.SaveChanges();
                }

                // 删除记录
                var deleteProduct = context.Products.Find(2); // 假设要删除 Id 为 2 的产品
                if (deleteProduct != null)
                {
                    context.Products.Remove(deleteProduct);
                    context.SaveChanges();
                }
            }
        }
    }
}

解释说明:

  • Entity Framework 是 C# 中常用的 ORM(对象关系映射)框架,它允许开发者通过操作对象来与数据库进行交互,而无需编写大量的 SQL 语句。
  • DbContext 类是 Entity Framework 的核心类,用于管理实体的生命周期和与数据库的连接。
  • DbSet 表示数据库中的表,T 是对应的实体类。
  • Add(), Remove(), 和 SaveChanges() 方法用于添加、删除和保存更改到数据库。
  • Find() 方法用于根据主键查找实体。
  • ToList() 方法将查询结果转换为列表。

这个示例展示了如何使用 Entity Framework 进行基本的 CRUD(创建、读取、更新、删除)操作。

上一篇:c#invoke

下一篇:c#socket

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站