SqlServer 数据库
1.DB First
现有 DB, 生成 edmx 文件
贴一下生成的 model
- //------------------------------------------------------------------------------
- // <auto-generated>
- // 此代码已从模板生成.
- //
- // 手动更改此文件可能导致应用程序出现意外的行为.
- // 如果重新生成代码, 将覆盖对此文件的手动更改.
- // </auto-generated>
- //------------------------------------------------------------------------------
- namespace Ruanmou.EFDBFirst
- {
- using System;
- using System.Collections.Generic;
- public partial class JD_Commodity_001
- {
- public int Id { get; set; }
- public Nullable<long> ProductId { get; set; }
- public Nullable<int> CategoryId { get; set; }
- public string Title { get; set; }
- public Nullable<decimal> Price { get; set; }
- public string Url { get; set; }
- public string ImageUrl { get; set; }
- }
- }
- 2.Code First
有数据库, 从数据库获得 model, 就是这个
贴一下生成的 Model, 和 DB First 的不太一样, 长度 attribute 加上了
- [Table("JD_Commodity_001")]//1 特性
- public partial class JDCommodity001
- {
- [Key]
- public int Id { get; set; }
- public long? ProductId { get; set; }
- //[ForeignKey]
- [Column("CategoryId")]
- public int? ClassId { get; set; }
- [StringLength(500)]
- public string Title { get; set; }
- public decimal? Price { get; set; }
- [StringLength(1000)]
- public string Url { get; set; }
- [StringLength(1000)]
- public string ImageUrl { get; set; }
- }
如果数据库字段或表名和 model 的不一样 (比如想去掉下划线) 可以有 3 种方式, 方式 1 见上图, Model 上或属性上加 attribute
方式 2 在 OnModelCreating 里添加映射, code first 的 OnModelCreating 和 DB first 的不一样, db 的什么也没写, 截图下 code first 的 OnModelCreating
代码, 启动时可以完成数据库和代码结构的同步
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- // 启动时可以完成数据库和代码结构的同步
- //new CreateDatabaseIfNotExists<codeFirstDbContext>();// 默认 不存在就创建
- //new DropCreateDatabaseAlways<codeFirstDbContext>();// 每次都删除重建
- //new DropCreateDatabaseIfModelChanges<codeFirstDbContext>();
- //Database.SetInitializer<codeFirstDbContext>(new DropCreateDatabaseIfModelChanges<codeFirstDbContext>());
- // 对不起 数据都没了.. 测试 / 快速部署 其实这里还可以完成数据初始化
- // 请一定小心
- modelBuilder.Entity<JDCommodity002>()
- .ToTable("JD_Commodity_002")
- .Property(c => c.ClassId)
- .HasColumnName("CategoryId");//2 链式 API
- modelBuilder.Configurations.Add(new JDCommodity003Mapping());//3 映射文件
- modelBuilder.Entity<Category>()
- .Property(e => e.Code)
- .IsUnicode(false);
方式 3 Mapping 的方式, 写个 Mapping 文件, 上面的代码有, 据说没什么人用
Oracle 数据库
可能引用这个就可以用吧
DB first , OnModelCreating 什么也没写 model 还是没有长度的 attribute
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- throw new UnintentionalCodeFirstException();
- }
这个是 EF5
- <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework,
- Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"requirePermission="false" />
模型管理器管理外键, 因为名字不一样看着不开心, 全改成 FK 开头的了用 Powerdesigner 改的, 获取的更新,
来源: https://www.cnblogs.com/kongsq/p/9785013.html