Linq InsertOnSubmit,DeleteOnSubmit和更新无法正常工作

时间:2013-04-07 13:52:31

标签: linq insertonsubmit

我看了几篇与InsertOnSubmit相关的帖子没有用,但没有一个能解决我的问题。下面是我的代码,我在我的BackupPlan表中手动插入一条记录,当我运行一个linq时,从数据库中选择记录,我尝试在下面插入的2条新记录返回并显示在日志中,但是当我在服务器资源管理器中检查时 - >数据连接 - >表BackupPlan只有手动插入的记录而不是新记录。我也尝试更新现有记录和删除没有成功,没有任何异常。此外,我添加了一个列Id并设置为我的BackupPlan表的主键,检查了db.GetChangeSet()并返回2个插入语句正在等待,但db.SubmitChanges()运行后没有成功。知道我在这里缺少什么??? :(

using System.Data.Linq.Mapping;

namespace Storage.Models
{
    [Table(Name = "BackupPlan")]
    public class BackupPlan
    {
        [Column(IsPrimaryKey = true, IsDbGenerated = true)]
        public int Id;

        [Column]
        public string Name;

        [Column]
        public string Description;
    }
}

using System.Data.Linq;
using Storage.Models;

namespace Storage
{
    public partial class Repository : DataContext
    {
        public Table<BackupPlan> BackupPlans;
        public Repository(string connection):base(connection){}
    }
}

using System;
using System.Data.Linq;
using System.Linq;
using Storage.Models;
using Storage.Properties;

namespace Storage
{
    class Test
    {
        static void Main(string[] args)
        {
            try
            {                
                var settings = new Settings();
                var db = new Repository(settings.DatabaseConnectionString)
                             {Log = Console.Out, ObjectTrackingEnabled = true};                


                var backupPlan1 = new BackupPlan() {Description = "This is my first backup plan!", Name = "B Plan"};                
                db.BackupPlans.InsertOnSubmit(backupPlan1);                

                var backupPlan2 = new BackupPlan() {Description = "This is my first backup plan 2!", Name = "B22 Plan"};
                db.BackupPlans.InsertOnSubmit(backupPlan2);

                var t = db.GetChangeSet(); //shows that 2 inserts are pending

                db.SubmitChanges();   // when i run this method i check my table but there are no any new records                         

                var q = from b in db.BackupPlans
                        select b;
                foreach (var backupPlan in q)
                {
                    Console.WriteLine("\n{0}", backupPlan.Name);
                }
                Console.ReadKey();              
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadKey();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

http://dean-o.blogspot.com/2010/03/mind-your-copy-to-output-directory.html

您构建程序,它将数据库文件复制到Bin / Debug,然后您写入该副本。

下次构建时,它会用新副本覆盖刚写入的数据库。将其更改为不复制。