本文共 3073 字,大约阅读时间需要 10 分钟。
本工具通过修改GitHub上开源项目,扩展了原始作者的工作,实现了一对多实体类的增删改查操作,并采取了Repository设计模式。同时,页面布局进行了优化,新增了DynamicData动态字段。该工具适用于VS.NET 2013及以上版本的Web Forms项目,能够根据事先定义的Entity类自动生成查询、新增、修改和删除页面及后台操作。
public class Product{ public int Id { get; set; } [Display(Name = "商品编码")] [MaxLength(10)] [Required] public string SKU { get; set; } [Display(Name = "品名")] [MaxLength(50)] [Required] public string Name { get; set; } [Display(Name = "规格")] [MaxLength(20)] public string Model { get; set; } [Display(Name = "单位")] [MaxLength(10)] public string Unit { get; set; } [Display(Name = "单价")] public decimal Price { get; set; } [Display(Name = "数量")] public int Qty { get; set; }}
public class Company{ public Company() { Departments = new HashSet(); } [Key] [Display(Name = "系统编码")] public int Id { get; set; } [Display(Name = "公司名称")] [MaxLength(10)] [Required] public string Name { get; set; } [Display(Name = "地址")] [MaxLength(50)] public string Address { get; set; } [Display(Name = "联系人")] [MaxLength(10)] public string ContactName { get; set; } [Display(Name = "联系电话")] [MaxLength(20)] public string ContactPhone { get; set; } public virtual ICollection Departments { get; set; }}public class Department{ public Department() { } [Key] [Display(Name = "系统编码")] public int Id { get; set; } [Display(Name = "部门名称")] [Required] [MaxLength(20)] public string Name { get; set; } public int Company_Id { get; set; } [ForeignKey("Company_Id")] public virtual Company Company { get; set; }}
在App_Start目录下的RouteConfig.cs中添加以下路由配置:
public static class RouteConfig{ public static void RegisterRoutes(RouteCollection routes) { var settings = new FriendlyUrlSettings { AutoRedirectMode = RedirectMode.Permanent }; routes.EnableFriendlyUrls(settings); // 添加路由配置 var defaultModel = new MetaModel(true); defaultModel.RegisterContext(new ModelProvider( () => new WebAPP.Models.MyDbContext(), new ContextConfiguration { ScaffoldAllTables = true } )); }}
项目目录下DynamicData文件夹支持添加新的动态字段(如DateTime),使GridView和编辑页面更加灵活。
编译后运行项目,访问相关页面即可完成数据操作。新增页面支持文件上传和数据验证,修改页面保留所有动态字段信息。
通过以上步骤,可以轻松完成ASP.NET Web Forms项目的CRUD操作,充分发挥Repository模式的优势。
转载地址:http://bvgfk.baihongyu.com/