CodeFirst 代码先行,只关心业务,需要什么对象就写什么对象;
Nuget引入程序集
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.SqlServer.Design
Microsoft.EntityFrameworkCore.Tools
生成迁移文件
命令: add-migration Init001 添加迁移文件
update-database 根据最新的迁移文件生成数据库
更新数据库
Commodity
public partial class Commodity
{
public int Id { get; set; }
public long? ProductId { get; set; }
public int? CategoryId { get; set; }
public string? Title { get; set; }
public decimal? Price { get; set; }
public string? Url { get; set; }
public string? ImageUrl { get; set; }
}
CompanyInfo
public partial class CompanyInfo
{
public CompanyInfo()
{
SysUsers = new HashSet<SysUser>();
}
public int Id { get; set; }
public string? CompanyName { get; set; }
public DateTime? CreateTime { get; set; }
public int CreatorId { get; set; }
public int? LastModifierId { get; set; }
public DateTime? LastModifyTime { get; set; }
public virtual ICollection<SysUser> SysUsers { get; set; }
}
SysUser
public partial class SysUser
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Password { get; set; }
public int Status { get; set; }
public string? Phone { get; set; }
public string? Mobile { get; set; }
public string? Address { get; set; }
public string? Email { get; set; }
public long? Qq { get; set; }
public string? WeChat { get; set; }
public int? Sex { get; set; }
public DateTime? LastLoginTime { get; set; }
public DateTime? CreateTime { get; set; }
public int? CreateId { get; set; }
public DateTime? LastModifyTime { get; set; }
public int? LastModifyId { get; set; }
public int? CompanyId { get; set; }
public virtual CompanyInfo? Company { get; set; }
}
CustomerDbContext
public partial class CustomerDbContext : DbContext
{
public CustomerDbContext()
{
}
public CustomerDbContext(DbContextOptions<CustomerDbContext> options)
: base(options)
{
}
public virtual DbSet<Commodity> Commodities { get; set; } = null!;
public virtual DbSet<CompanyInfo> CompanyInfo { get; set; } = null!;
public virtual DbSet<SysUser> SysUsers { get; set; } = null!;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=LearnCustomerDB_New;User ID=sa;Password=123456");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Commodity>(entity =>
{
entity.ToTable("Commodity");
entity.Property(e => e.ImageUrl)
.HasMaxLength(1000)
.IsUnicode(false);
entity.Property(e => e.Price).HasColumnType("decimal(18, 2)");
entity.Property(e => e.Title)
.HasMaxLength(500)
.IsUnicode(false);
entity.Property(e => e.Url)
.HasMaxLength(1000)
.IsUnicode(false);
});
modelBuilder.Entity<CompanyInfo>(entity =>
{
entity.ToTable("Company");
entity.Property(e => e.CreateTime).HasColumnType("datetime");
entity.Property(e => e.LastModifyTime).HasColumnType("datetime");
entity.Property(e => e.CompanyName)
.HasMaxLength(50)
.IsUnicode(false);
});
modelBuilder.Entity<SysUser>(entity =>
{
entity.ToTable("SysUser");
entity.Property(e => e.Address)
.HasMaxLength(500)
.IsUnicode(false);
entity.Property(e => e.CreateTime).HasColumnType("datetime");
entity.Property(e => e.Email)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.LastLoginTime).HasColumnType("datetime");
entity.Property(e => e.LastModifyTime).HasColumnType("datetime");
entity.Property(e => e.Mobile)
.HasMaxLength(12)
.IsUnicode(false);
entity.Property(e => e.Name)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.Password)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.Phone)
.HasMaxLength(12)
.IsUnicode(false);
entity.Property(e => e.Qq).HasColumnName("QQ");
entity.Property(e => e.WeChat)
.HasMaxLength(50)
.IsUnicode(false);
entity.HasOne(d => d.Company)
.WithMany(p => p.SysUsers)
.HasForeignKey(d => d.CompanyId)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_SysUser_CompanyInfo");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
EFCoreCodeFirst
public class EFCoreCodeFirst
{
public static void Show()
{
using (CustomerDbContext context = new CustomerDbContext())
{
context.Database.EnsureDeleted(); //删除数据库
context.Database.EnsureCreated();//创建全新的数据库
}
}
}
Program.cs
// See https://aka.ms/new-console-template for more information
using Learn.NET6.DemoTest;
Console.WriteLine("Hello, World!");
//EFCoreDbFirst.Show();
EFCoreCodeFirst.Show();
补充:EntityFrameCore6.0-LinqToSql
public class EFQueryTest
{
public static void Show()
{
#region 其他查询
using (CustomerDbContext dbContext = new CustomerDbContext())
{
{
var ids = new int[] { 54, 55, 56, 57, 58, 59, 60, 61, 63 };
var list = dbContext.SysUsers.Where(u => 1 == 1 && !(ids.Contains(u.Id)));//in查询
foreach (var user in list)
{
Console.WriteLine(user.Name);
}
}
{
var list = from u in dbContext.SysUsers
where new int[] { 54, 55, 56, 57, 58, 59, 60, 61, 63 }.Contains(u.Id)
select u;
foreach (var user in list)
{
Console.WriteLine(user.Name);
}
}
{
var list = dbContext.SysUsers.Where(u => new int[] { 54, 55, 56, 57, 58, 59, 60, 61, 63 }.Contains(u.Id))
.OrderBy(u => u.Id) //排序--升序
.OrderByDescending(c => c.Name)
.Select(u => new //投影
{
Name = u.Name,
Pwd = u.Password
}).Skip(3).Take(5); //跳过三条 再获取5条
foreach (var user in list)
{
Console.WriteLine(user.Name);
}
}
{
var list = dbContext.SysUsers.Where(u => u.Name.StartsWith("Richard") && u.Name.EndsWith("小王子"))
.Where(u => u.Name.EndsWith("小王子"))
.Where(u => u.Name.Contains("小王子"))
.Where(u => u.Name.Length < 10)
.OrderBy(u => u.Id);
foreach (var user in list)
{
Console.WriteLine(user.Name);
}
}
{
var list = from u in dbContext.CompanyInfo
join c in dbContext.SysUsers on u.Id equals c.CompanyId
where new int[] { 1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 14, 17 }.Contains(u.Id)
select new
{
Name = u.CompanyName,
UserName = c.Name,
Address = c.Address
};
foreach (var user in list)
{
System.Console.WriteLine($"{user.Name}-{user.Address}");
}
}
}
using (CustomerDbContext dbContext = new CustomerDbContext())
{
{
try
{
string sql = "Update dbo.SysUser Set Password='小王子' WHERE Id=@Id";
SqlParameter parameter = new SqlParameter("@Id", 1);
int flag = dbContext.Database.ExecuteSqlRaw(sql, parameter);
}
catch (Exception ex)
{
throw ex;
}
}
}
using (CustomerDbContext dbContext = new CustomerDbContext())
{
{
IDbContextTransaction trans = null;
try
{
trans = dbContext.Database.BeginTransaction();
string sql = "Update dbo.SysUser Set Password='Test00xx' WHERE Id=@Id";
SqlParameter parameter = new SqlParameter("@Id", 3843);
dbContext.Database.ExecuteSqlRaw(sql, parameter);
string sql1 = "Update dbo.SysUser Set Password='Test00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abc' WHERE Id=@Id";
SqlParameter parameter1 = new SqlParameter("@Id", 3843);
dbContext.Database.ExecuteSqlRaw(sql1, parameter1);
trans.Commit();
}
catch (Exception ex)
{
if (trans != null)
trans.Rollback();
}
finally
{
trans.Dispose();
}
}
}
#endregion
}
}