1

我需要在一个应用程序中合并

  1. 编译前从 DB 生成的代码到 EDMX 文件
  2. 应用程序本身在运行时生成和编译的代码,其中生成的代码使用 CodeFirst 访问数据库。

备注:1.和2.中的代码有不同的DbContexts,访问同一个数据库,但不同的表。

看起来,当我在不同的事务范围内使用类型 1. 和 2. 的实例时,一切正常。但是当我尝试在一个事务范围内一起使用它们时,我得到了错误(如果首先调用 EDMX)

System.Reflection.TargetInvocationException: Exception has been thrown by the ta
rget of an invocation. ---> System.Data.ProviderIncompatibleException: An error
occurred while getting provider information from the database. This can be cause
d by Entity Framework using an incorrect connection string. Check the inner exce
ptions for details and ensure that the connection string is correct. ---> System
.Data.ProviderIncompatibleException: **The provider did not return a ProviderManif
estToken string.** ---> System.Transactions.TransactionException: **The operation is
 not valid for the state of the transaction.**

和错误(如果首先使用 CodeFirst)

System.Data.MetadataException: Schema specified is not valid. Errors:
(0,0) : error 0175: **The specified store provider cannot be found in the configur
ation, or is not valid.**
   at System.Data.Metadata.Edm.StoreItemCollection.Loader.ThrowOnNonWarningErrors()

为了使我的情况更加复杂,我必须添加以下内容:描述的行为只有在数据库位于远程服务器上时才有。如果我使用本地数据库,一切看起来都很好。我的怀疑是分布式事务协调器可以发挥它的作用......

主要问题:是否可以在一个 TransactionScope 中结合 EDMX 和 CodeFirst。如果是,那怎么办?

任何帮助,将不胜感激。米洛斯

4

2 回答 2

0

我首先使用代码保存到两个不同的数据库,但出现错误连接字符串错误,所以我这样做了,它成功了....

try
{
    using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
        MegaBotExtractorDBContext2 db = new MegaBotExtractorDBContext2();
        MegaBotExtractorDBContext db1 = new MegaBotExtractorDBContext();
        FullUri newUri = new FullUri();
        HostUri NewHostUri = new HostUri { HostUriName = "google10.com" };
        db1.HostUris.Add(NewHostUri);
        db1.SaveChanges();

        using (TransactionScope ts2 = new TransactionScope(TransactionScopeOption.RequiresNew))
        {
            db.FullUris.Add(newUri);
            db.SaveChanges();
            ts2.Complete();
            ts.Complete();
        }
    }
}
catch { }
于 2012-11-06T10:00:29.650 回答
0

CodeFirst 基于您的类创建 EDMX,并且无法加载现有的 edmx 文件。但是,您可以从您的数据库生成类(例如使用 EF Power Tools)并配置您的模型,以便您的 CodeFirst 应用程序生成的 EDMX 与您要加载的相同。您可以将 TransactionScope 与实体框架一起使用。您收到的错误消息与事务范围无关,而是与缺少或错误使用的提供程序有关。

于 2012-10-12T18:02:22.033 回答