问题从xml文件创建数据库

时间:2012-09-14 13:23:31

标签: c# .net entity-framework ef-code-first

我在从xml文件创建数据库时遇到问题。

我正在监视特定文件的目录,当更新此文件时,我调用我的方法。

每次我运行我的代码时,它都是第一次按预期工作(但是),但是第二次调用我的方法时,我得到以下异常:

[System.Data.SqlClient.SqlException] = {“无法打开数据库\”MyDatabase \“登录请求。登录失败。\ r \ n登录失败,用户'DOM \ myuseraccount'。”}

public bool ImportXmlToDatabase(string filename)
    {
      try
      {
        var path = Assembly.GetExecutingAssembly().Location;
        filename = path.Substring(0, path.LastIndexOf('\\') + 1) + filename;
        if (!File.Exists(filename))
        {
          Log(LogMessageType.Warning, "File didn't exist: " + filename);
          return false;
        }
        using (var inputStream = new FileStream(filename, FileMode.Open))
        {
          var serializer = new DataContractSerializer(typeof(IChangeTrackingEntity), new List<Type>(), int.MaxValue, false, true /* preserveObjectReferences */, null, new SharedTypeResolver());
          Database.Delete("MyDatabase");
          using (var repository = new DbRepository("MyDatabase"))
          {
            var list = (IEnumerable)serializer.ReadObject(inputStream);
            foreach (dynamic obj in list)
            {
              repository.Insert(obj);
            }
            repository.SaveChanges();
          }
        }
        return true;
      }
      catch (Exception exc)
      {
        Log(LogMessageType.Error, "Did not manage to import data from the xml to the database. The following error occured: " + exc);
        return false;
      }
    }

0 个答案:

没有答案