1、定义一个基础模板类
namespace WebApplication1.Models { /// <summary> /// 可持久到数据库的领域模型的基类。 /// </summary> [Serializable] public abstract class EntityBase<TKey> { #region 构造函数 /// <summary> /// 数据实体基类 /// </summary> protected EntityBase() { IsDeleted = false; AddDate = DateTime.Now; } #endregion #region 属性 [Key] public TKey Id { get; set; } /// <summary> ///获取或设置 获取或设置是否禁用,逻辑上的删除,非物理删除 /// </summary> public bool IsDeleted { get; set; } /// <summary> /// 获取或设置 添加时间 /// </summary> [DataType(DataType.DateTime)] public DateTime AddDate { get; set; } #endregion } }
2、定义实体类
namespace WebApplication1.Models { public partial class SystemAreas : EntityBase<string> { public SystemAreas() { this.ChildSystemAreas = new HashSet<SystemAreas>(); } public string Name { get; set; } public string ParentId { get; set; } public virtual ICollection<SystemAreas> ChildSystemAreas { get; set; } public virtual SystemAreas ParentSystemAreas { get; set; } } }
3、插入数据
public ActionResult Index() { SystemAreas sa = new SystemAreas() { Id="12", Name = "test" }; TestDbContext db = new TestDbContext(); db.Set<SystemAreas>().Add(sa); db.SaveChanges(); return View(); }