本文向大家介绍Ling to sql更新实体,可能好多人还不了解Ling to sql更新实体,没有关系,看完本文你肯定有不少收获,希望本文能教会你更多东西。
Ling to sql更新实体非常费劲!一般网上的例子中都是一下这样的。
- Customer cust = db.Customers.First(c => c.CustomerID == "ALFKI");
- cust.ContactTitle = "Vice President";
- db.SubmitChanges();
但是,貌似在分层系统中,数据库操作会写到数据访问层,定义实体,抽象出接口。
实体类 :
- /// <summary>
- /// 计划任务
- /// </summary>
- [Table(Name = "EDM_TaskPlan")]
- public class TaskPlan
- {
- /// <summary>
- /// 计划编码
- /// </summary>
- [Column(IsDbGenerated=true,IsPrimaryKey=true,Name="PlanID")]
- public int PlanID { get; set; }
- /// <summary>
- /// 任务名称
- /// </summary>
- [Column(Name="PlanName")]
- public string Name { get; set; }
- /// <summary>
- /// 任务描述
- /// </summary>
- [Column]
- public string Description { get; set; }
- /// <summary>
- /// 星期一定义
- /// </summary>
- [Column]
- public string MondayDef { get; set; }
- /// <summary>
- /// 星期二定义
- /// </summary>
- [Column]
- public string TuesdayDef { get; set; }
- /// <summary>
- /// 星期三定义
- /// </summary>
- [Column]
- public string WednesdayDef { get; set; }
- /// <summary>
- /// 星期四定义
- /// </summary>
- [Column]
- public string ThursdayDef { get; set; }
- /// <summary>
- /// 星期五定义
- /// </summary>
- [Column]
- public string FridayDef { get; set; }
- /// <summary>
- /// 星期六定义
- /// </summary>
- [Column]
- public string SaturdayDef { get; set; }
- /// <summary>
- /// 星期日定义
- /// </summary>
- [Column]
- public string SundayDef { get; set; }
- }
数据访问接口 :
- /// <summary>
- /// 任务计划数据访问接口
- /// </summary>
- public interface ITaskPlanDao
- {
- /// <summary>
- /// 查找全部
- /// </summary>
- /// <returns></returns>
- TaskPlan[] FindAll();
- /// <summary>
- /// 根据编码查找
- /// </summary>
- /// <param name="id">计划任务编码</param>
- /// <returns></returns>
- TaskPlan FindByID(int id);
- /// <summary>
- /// 保存或更新
- /// </summary>
- /// <param name="taskPlan">任务计划对象</param>
- /// <returns></returns>
- int SaveOrUpdate(TaskPlan taskPlan);
- /// <summary>
- /// 根据编码删除
- /// </summary>
- /// <param name="id">任务计划编码</param>
- /// <returns></returns>
- void DeleteByID(int id);
- }
但是我在Ling to sql更新实体的时候出现了问题。
- dbContext.Attach(taskPlan);
- //根本不会更新
- dbContext.Attach(taskPlan,true);
- //An entity can only be attached as modified without original state if it
- //declares a version member or does not have an update check policy
- dbContext.Attach(taskPlan,this.FindByID(taskPlan.PlanID));
- //Cannot add an entity with a key that is already in use.
网上也有解决方案,就是加IsVersion字段,感觉怪怪的。
【编辑推荐】