網站首頁 編程語言 正文
DbContext類有一個OnModelCreating方法,它用于流利地配置領域類到數(shù)據(jù)庫模式的映射。下面我們以fluent API的方式來定義映射。
首先,先將Product類注釋掉,重新編寫該類,重新編寫后的Product類:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EFFluentAPI.Model { public class Product { public int ProductNo { get; set; } public string ProductName { get; set; } public double ProductPrice { get; set; } } }
然后在數(shù)據(jù)庫上下文Context類中的OnModelCreating方法中使用fluent API來定義Product表的數(shù)據(jù)庫模式:
using EFFluentAPI.Model; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EFFluentAPI.EFContext { public class Context:DbContext { public Context() : base("DbConnection") { } public DbSetProducts { get; set; } /// /// 重新OnModelCreating方法 /// /// protected override void OnModelCreating(DbModelBuilder modelBuilder) { //映射到表Product,ProductNo和ProductName作為復合主鍵 modelBuilder.Entity().ToTable("Product").HasKey(p=>new {p.ProductNo,p.ProductName}); //ProductNo映射到數(shù)據(jù)表中的列名是Id modelBuilder.Entity ().Property(p => p.ProductNo).HasColumnName("Id"); modelBuilder.Entity ().Property(p => p.ProductName) .IsRequired() //設置ProductName是必須的,即不能為null,默認是可以為null的 .IsUnicode() //設置ProductName列為Unicode字符,實際上默認就是Unicode字符,所以該方法可以不寫。 .HasMaxLength(10); //設置ProductName列的最大長度是10 base.OnModelCreating(modelBuilder); } } }
modelBuilder.Entity
什么是POCO?
POCO是指Plain Old Class Object,也就是最基本的CLR Class,在原先的EF中,實體類通常是從一個基類繼承下來的,而且?guī)в写罅康膶傩悦枋?。而POCO則是指最原始的Class,換句話說這個實體的Class僅僅需要從Object繼承即可,不需要從某一個特定的基類繼承。主要是配合Code First使用。Code First則是指我們先定義POCO這樣的實體Class,然后生成數(shù)據(jù)庫。實際上現(xiàn)在也可以使用Entity Framweork Power tools將已經存在的數(shù)據(jù)庫反向生成POCO的Class(不通過edmx文件)。
程序運行后創(chuàng)建的數(shù)據(jù)庫如下圖所示:
原文鏈接:https://www.cnblogs.com/dotnet261010/p/7418547.html
相關推薦
- 2022-03-11 UE4 添加自己項目的AutomationProject,解決報錯Failed to find co
- 2022-11-21 正則表達式RegExp語法與用法詳解_正則表達式
- 2022-07-06 C語言實現(xiàn)字符串字符反向排列的方法詳解_C 語言
- 2022-04-15 C#的并發(fā)機制優(yōu)秀在哪你知道么_C#教程
- 2022-03-15 C#實現(xiàn)時間戳與標準時間的互轉_C#教程
- 2022-05-22 Nginx服務安裝及軟件升級_nginx
- 2022-11-14 開發(fā)板NFS掛載方案
- 2022-09-26 python?opencv實現(xiàn)目標外接圖形_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支