创建 Entity Framework Core 模型,将 Suppliers、Products、Categories 表格映射到对应的实体内容:

Suppliers 实体:

public class Supplier
{
    public int SupplierId { get; set; } 
    public string CompanyName { get; set; } 
    public string ContactName { get; set; } 
    public string ContactTitle { get; set; } 
    public string Address { get; set; } 
    public string City { get; set; } 
    public string Region { get; set; } 
    public string PostalCode { get; set; } 
    public string Country { get; set; } 
    public string Phone { get; set; } 
    public string Fax { get; set; } 
    public string HomePage { get; set; } 
    public ICollection<Product> Products { get; set; } 
}

Products 实体:

public class Product
{
    public int ProductId { get; set; } 
    public string ProductName { get; set; } 
    public int SupplierId { get; set; } 
    public Supplier Supplier { get; set; } 
    public int? CategoryId { get; set; } 
    public Category Category { get; set; } 
    public string QuantityPerUnit { get; set; } 
    public decimal UnitPrice { get; set; } 
    public short UnitsInStock { get; set; } 
    public short UnitsOnOrder { get; set; } 
    public short ReorderLevel { get; set; } 
    public bool Discontinued { get; set; } 
}

Categories 实体:

public class Category
{
    public int CategoryId { get; set; } 
    public string CategoryName { get; set; } 
    public string Description { get; set; } 
    public ICollection<Product> Products { get; set; } 
}

代码说明:

  • 以上代码展示了 Suppliers、Products 和 Categories 实体类的定义,每个实体类都对应数据库中的一个表格。
  • 实体类中的属性对应表格中的列,例如 Supplier 实体中的 CompanyName 属性对应 Suppliers 表格中的 CompanyName 列。
  • ICollection<Product> 属性表示 Supplier 和 Product 之间的多对多关系,类似地,ICollection<Product> 属性表示 Category 和 Product 之间的多对多关系。

如何使用这些实体:

  1. 创建一个数据库上下文类,并使用 DbContext 类来配置数据库连接和实体映射关系。
  2. 使用 DbSet 属性来表示每个实体类对应的数据库集合,例如 DbSet<Supplier>DbSet<Product>DbSet<Category>
  3. 使用数据库上下文类来执行数据操作,例如添加、删除、修改和查询数据。

更多信息:

示例:

using Microsoft.EntityFrameworkCore;  
  
public class MyDbContext : DbContext  
{  
    public DbSet<Supplier> Suppliers { get; set; }  
    public DbSet<Product> Products { get; set; }  
    public DbSet<Category> Categories { get; set; }  
  
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
    {  
        optionsBuilder.UseSqlServer('your-connection-string'); // 使用 SQL Server 数据库  
    }  
}  

请注意将 'your-connection-string' 替换成你实际的数据库连接字符串。

Entity Framework Core 模型映射:Suppliers、Products、Categories 实体示例

原文地址: https://www.cveoy.top/t/topic/oim6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录