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();
}
}
}
}
}
T 是对应的实体类。这个示例展示了如何使用 Entity Framework 进行基本的 CRUD(创建、读取、更新、删除)操作。
上一篇:c#invoke
下一篇:c#socket
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站