简体   繁体   English

实体框架无法保存生产环境中的更改

[英]Entity framework not saving changes in production enviroment

I am writing a desktop application that works with EF and MySql. 我正在编写可与EF和MySql一起使用的桌面应用程序。 There is a mapping of each type created by the EF to a local type. EF创建的每种类型都有到本地类型的映射。 When testing the wrapper methods using the unit testing framework supplied by Visual Studio, all the test run -and I see the information going in and out of the database. 当使用Visual Studio提供的单元测试框架测试包装方法时,所有的测试都会运行-并且我看到信息进出数据库。 However, when I run the same code from a temp console program I added for integration tests, the EF throws the following exception: 但是,当我从为集成测试添加的临时控制台程序运行相同的代码时,EF抛出以下异常:

System.NullReferenceException: Object reference not set to an instance of an object.
   at MySql.Data.MySqlClient.MySqlClientFactory.get_MySqlDbProviderServicesInstance()
   at MySql.Data.MySqlClient.MySqlClientFactory.System.IServiceProvider.GetService(Type serviceType)
   at System.Data.Common.DbProviderServices.GetProviderServices(DbProviderFactory factory)
   at System.Data.Metadata.Edm.StoreItemCollection.Loader.InitializeProviderManifest(Action`3 addError)
   at System.Data.Metadata.Edm.StoreItemCollection.Loader.OnProviderManifestTokenNotification(String token, Action`3 addError)
   at System.Data.EntityModel.SchemaObjectModel.Schema.HandleProviderManifestTokenAttribute(XmlReader reader)
   at System.Data.EntityModel.SchemaObjectModel.Schema.HandleAttribute(XmlReader reader)
   at System.Data.EntityModel.SchemaObjectModel.SchemaElement.ParseAttribute(XmlReader reader)
   at System.Data.EntityModel.SchemaObjectModel.SchemaElement.Parse(XmlReader reader)
   at System.Data.EntityModel.SchemaObjectModel.Schema.HandleTopLevelSchemaElement(XmlReader reader)
   at System.Data.EntityModel.SchemaObjectModel.Schema.InternalParse(XmlReader sourceReader, String sourceLocation)
   at System.Data.EntityModel.SchemaObjectModel.Schema.Parse(XmlReader sourceReader, String sourceLocation)
   at System.Data.EntityModel.SchemaObjectModel.SchemaManager.ParseAndValidate(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, SchemaDataModelOption dataModel, AttributeValueNotification providerNotification, AttributeValueNotification providerManifestTokenNotification, ProviderManifestNeed
ed providerManifestNeeded, IList`1& schemaCollection)
   at System.Data.Metadata.Edm.StoreItemCollection.Loader.LoadItems(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths)
   at System.Data.Metadata.Edm.StoreItemCollection.Init(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths, Boolean throwOnError, DbProviderManifest& providerManifest, DbProviderFactory& providerFactory, String& providerManifestToken, Memoizer`2& cachedCTypeFunction)
   at System.Data.Metadata.Edm.StoreItemCollection..ctor(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths)
   at System.Data.Metadata.Edm.MetadataCache.StoreMetadataEntry.LoadStoreCollection(EdmItemCollection edmItemCollection, MetadataArtifactLoader loader)
   at System.Data.Metadata.Edm.MetadataCache.StoreItemCollectionLoader.LoadItemCollection(StoreMetadataEntry entry)
   at System.Data.Metadata.Edm.MetadataCache.LoadItemCollection[T](IItemCollectionLoader`1 itemCollectionLoader, T entry)
   at System.Data.Metadata.Edm.MetadataCache.GetOrCreateStoreAndMappingItemCollections(String cacheKey, MetadataArtifactLoader loader, EdmItemCollection edmItemCollection, Object& entryToken)
   at System.Data.EntityClient.EntityConnection.LoadStoreItemCollections(MetadataWorkspace workspace, DbConnection storeConnection, DbProviderFactory factory, DbConnectionOptions connectionOptions, EdmItemCollection edmItemCollection, MetadataArtifactLoader artifactLoader)
   at System.Data.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean initializeAllCollections)
   at System.Data.EntityClient.EntityConnection.InitializeMetadata(DbConnection newConnection, DbConnection originalConnection, Boolean closeOriginalConnectionOnFailure)
   at System.Data.EntityClient.EntityConnection.Open()
   at System.Data.Objects.ObjectContext.EnsureConnection()
   at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Objects.ObjectContext.SaveChanges()
   at DataAccess.PhoneTypeAccess.AddNewPhoneType(PhoneType newPhoneType) in C:\Users\Mordechai\Desktop\Progaming\GitHub\VirtualGabbai\VirtGabbai\DataAccess\PhoneTypeAccess.cs:line 66
   at TempUI.Program.Main(String[] args) in C:\Users\Mordechai\Desktop\Progaming\GitHub\VirtualGabbai\VirtGabbai\TempUI\Program.cs:line 17

Here is the code i run in program.cs 这是我在program.cs中运行的代码

static void Main(string[] args)
        {
            try
            {
                PhoneTypeAccess.AddNewPhoneType(new PhoneType(1, "phone"));
                var blah = PhoneTypeAccess.GetPhoneTypeById(1);
                Console.WriteLine(blah.ToString());
                //Cache.CacheData.t_phone_types.AddObject(t_phone_types.Createt_phone_types(1, "some Type"));
                //var thingOne = t_people.Createt_people(1);
                //Cache.CacheData.t_people.AddObject(thingOne);
                //Cache.CacheData.SaveChanges();
                //PhoneNumberAccess.AddNewPhoneNumber(new PhoneNumber(1, "some number", new PhoneType(1, "some type")));
                //var test = PhoneNumberAccess.GetPhoneNumberById(1);
                //Console.WriteLine(test.ToString
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

The test contains the following code 该测试包含以下代码

[TestMethod()]
    public void AddNewPhoneTypeTest()
    {
        PhoneType newPhoneType = new PhoneType(21, "phonetype:21");
        PhoneTypeAccess.AddNewPhoneType(newPhoneType);
        PhoneType actual = PhoneTypeAccess.GetPhoneTypeById(21);
        Assert.IsTrue(newPhoneType.Equals(actual));
    }

And the code being called is as follows 并且被调用的代码如下

 public static void AddNewPhoneType(PhoneType newPhoneType)
    {
        t_phone_types phoneTypeToAdd = PhoneTypeAccess.ConvertSingleLocalPhoneTypeToDbType(newPhoneType);
        Cache.CacheData.t_phone_types.AddObject(phoneTypeToAdd);
        Cache.CacheData.SaveChanges();
    }

When i went in with debug at the line Cache.CacheData.SaveChanges() , I get to the following code 当我在Cache.CacheData.SaveChanges()行进行调试时,进入以下代码

/// <summary>
/// Allows access to the cached data - but only a single (and constant) instance of it
///  -[the code can create another one but it will be a completly different set of data]-
/// </summary>
public static class Cache
{
    // Data members
    private static zera_leviEntities m_dsDataSet = new zera_leviEntities();

    /// <summary>
    /// Allows outside access to the main data set
    ///  - without letting the user access it any other way
    /// </summary>
    public static zera_leviEntities CacheData
    {
        get
        {
            return m_dsDataSet;
        }
    }
}

and the only thing I could see was the fact that in the entity set there really was no object. 我唯一能看到的是,在实体集中,确实没有对象。 but there was no indication as to why I've looked all over and didnt find anything that helped. 但是没有迹象表明我为何四处张望,却找不到任何帮助。 I am stuck until I get this running so I hope someone can help me Thank you 在执行此操作之前,我一直处于困境,所以希望有人可以帮助我,谢谢

Edit: Added in the conversion method 编辑:在转换方法中添加

private static t_phone_types ConvertSingleLocalPhoneTypeToDbType(PhoneType localTypePhoneType)
    {
        return t_phone_types.Createt_phone_types(localTypePhoneType._Id, localTypePhoneType.PhoneTypeName);
    }

The t_phone_types.Createt_phone_types() method is part of the EF t_phone_types.Createt_phone_types()方法是EF的一部分

Edit: I've managed to break the tests also now by changing the references in the whole solution to an updated version of the MySql Adapter Now the tests also throw the same exception. 编辑:现在,通过将整个解决方案中的引用更改为MySql Adapter的更新版本,我也设法打破了测试。现在,测试也引发了相同的异常。 In addition when building I get the following error: 另外在构建时,我收到以下错误:

Error 4: Could not load file or assembly 'MySql.Data, Version=6.7.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) C:\Users\Mordechai\Desktop\Progaming\GitHub\VirtualGabbai\VirtGabbai\Data\EntityCache.edmx

BUT, it will still run (just that it throws the exception) 但是,它仍然会运行(只是抛出异常)

Well...., I managed to figure out the problem after much trial and error. 好吧..,经过反复尝试,我设法找出了问题所在。 The MySQl adapter comes in 2 parts. MySQl适配器分为两个部分。 One for all connections and an additional piece for connecting specifically with EF. 一个用于所有连接,另一个用于专门与EF连接。 Now that I added the second dll it all runs fine. 现在,我添加了第二个dll,一切运行正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM