public class DefaultDbContext : DbContext
{
public DefaultDbContext()
{
}
public DbSet<User> Users { set; get; }
public DbSet<UserDetail> UserDetails { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string sqlConnection = "server=127.0.0.1;port=3306;user=root;password=123456;database=efcoredemo";
optionsBuilder.UseMySql(sqlConnection);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration<User>(new UserConfiguration());
modelBuilder.ApplyConfiguration<UserDetail>(new UserDetailConfiguration());
base.OnModelCreating(modelBuilder);
}
}
public class UserConfiguration : IEntityTypeConfiguration<User>
{
public UserConfiguration()
{
}
public void Configure(EntityTypeBuilder<User> builder)
{
builder.ToTable("user");
builder.HasIndex(q => q.IdCard).IsUnique();
builder.HasOne(q => q.UserDetail).WithOne(q=>q.User).HasForeignKey<User>(q => q.userDetailId);
}
}
public class UserDetailConfiguration : IEntityTypeConfiguration<UserDetail>
{
public UserDetailConfiguration()
{
}
public void Configure(EntityTypeBuilder<UserDetail> builder)
{
builder.ToTable("userdetail");
builder.Property(q => q.Work).HasMaxLength(500);
}
}
[Table("user")]
public class User
{
[Key]
public int Id { set; get; }
[Required]
public string IdCard { get; set; }
[Column("sex")]
public bool Sex { get; set; }
[Column("name")]
public string Name { set; get; }
[Column("createTime")]
public DateTime CreateTime { set; get; } = DateTime.Now;
[Column("modifyTime")]
public DateTime ModifyTime { set; get; } = DateTime.Now;
[Column("userDetailId")]
public int userDetailId { get; set; }
public UserDetail UserDetail { get; set; }
}
[Table("userdetail")]
public class UserDetail
{
[Key]
public int Id { get; set; }
[Column("email")]
[StringLength(50)]
public string Email { get; set; }
[Column("phone")]
[StringLength(20)]
public string Phone { get; set; }
[Column("note")]
[StringLength(200)]
public string Note { get; set; }
[Column("lastLoginTime")]
public DateTime LastLoginTime { get; set; }
[Column("work")]
public string Work { get; set; }
public User User { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
using (DefaultDbContext db = new DefaultDbContext())
{
//db.Database.MigrateAsync();
//db.Database.EnsureCreated();
var list = db.Database.GetPendingMigrations();
if (list.Count() > 0)
{
db.Database.MigrateAsync();
}
//var user = new User { Name = "张三", Sex = false, IdCard = "513701199109121331" };
//db.Users.Add(user);
//db.SaveChanges();
//System.Console.Write(db.Users.ToList());
Console.ReadKey();
}
}
}
来源:oschina
链接:https://my.oschina.net/u/4265074/blog/3220599