2010-09-07 35 views
0

您好我想创建一个基本的数据模型/层PLINQO/LINQ到SQL - 生成的实体自我保存方法?

的想法是有:

任务task = TaskRepository.GetTask(2);

task.Description =“任务已经改变”;

task.Save();

这可能吗?我试过了下面的代码

注意:TaskRepository.GetTask()方法分离了Task实体。

我希望这个工作,任何想法,为什么它不?

感谢

public partial class Task 
    { 
     // Place custom code here. 

     public void Save() 
     { 
      using (TinyTaskDataContext db = new TinyTaskDataContext { Log = Console.Out }) 
      { 
       db.Task.Attach(this); 


       db.SubmitChanges(); 
      } 
     } 


     #region Metadata 
     // For more information about how to use the metadata class visit: 
     // http://www.plinqo.com/metadata.ashx 
     [CodeSmith.Data.Audit.Audit] 
     internal class Metadata 
     { 
      // WARNING: Only attributes inside of this class will be preserved. 

      public int TaskId { get; set; } 

      [Required] 
      public string Name { get; set; } 

      [Now(EntityState.New)] 
      [CodeSmith.Data.Audit.NotAudited] 
      public System.DateTime DateCreated { get; set; } 

     } 

     #endregion 
    } 

回答

1

已经做了一些阅读中,我已经意识到我被错误地implmenting Repository模式。为了约定,我应该将Save方法添加到存储库中。

但是,我提交的关于提交断开数据集的实际问题是由于乐观并发。 datacontext的工作是跟踪它的实体状态。当实体断开连接时,你将失去该状态。

我发现你需要添加一个时间戳字段到数据库表中,或者我可以在我的dbml文件的每一列上设置UpdateCheck字段。

以下是关于断开的LINQ的UpdateCheck

一些有用的链接的一些信息和PLINQO

Great info on implementing the Repository pattern with LINQ

Short tutorial for implementing for updating and reattaching entities

Previously answer question

Rick Strahl on LINQ to SQL and attaching Entities

0

没有必要为此行(任务task =新的任务();)。上述应该工作,虽然我从来没有看到它以这种方式实施。你有没有想过使用经理?你是否遇到任何运行时错误?

感谢 -Blake Niemyjski

+0

对不起,我的错误,我应该删除Task task = new Task(); – Mantisimo 2010-09-08 07:06:50

+0

我希望以不连通的方式工作。从我看到的没有与上下文联系在一起的经理?...所以实际上我也有同样的问题? – Mantisimo 2010-09-08 07:09:14

+0

我已经读了关于使用版本库模板实现PLINQO的夜晚。 http://jonkruger.com/blog/2008/02/10/linq-to-sql-in-disconnectedn-tier-scenarios-saving-an-object/ – Mantisimo 2010-09-08 07:11:34