简体   繁体   中英

Generating Mapping views from code - EF6

https://msdn.microsoft.com/en-us/data/dn469601.aspx

I am trying to get the strategy mentioned in the linked article implemented in my huge codebase with over 500 entities to improve performance. I am stuck with the following issue.

System.Data.Entity.Core.EntityCommandCompilationException occurred
HResult=0x8013193B Message=An error occurred while preparing the command definition. See the inner exception for details.
Source= StackTrace:

Inner Exception 1: MappingException: The current model no longer matches the model used to pre-generate the mapping views, as indicated by the ViewsForBaseEntitySets3193163ce55837363333438629c877839ae9e7b7494500b6fd275844cda6d343.MappingHashValue property. Pre-generated mapping views must be either regenerated using the current model or removed if mapping views generated at runtime should be used instead. See http://go.microsoft.com/fwlink/?LinkId=318050 for more information on Entity Framework mapping views.

Here's what I have tried. There are a few gaps in the original article on how it needs to be implemented where I might have fallen prey.

Step 1: I have created a class that extends DBMappingViewCache.

public class EFDbMappingViewCache : DbMappingViewCache
    {
        protected static string _mappingHashValue = String.Empty;
        public override string MappingHashValue
        {
            get
            {
                return GetCachedHashValue();
            }
        }

        public override DbMappingView GetView(EntitySetBase extent)
        {
            Dictionary<string, string> dict = GetMappedViewFromCache();
            if (extent == null)
            {
                throw new ArgumentNullException("extent");
            }
            if(dict.ContainsKey(extent.Name))
            {
                return new DbMappingView(dict[extent.Name]);
            }
            return null;
        }


        public static string GetCachedHashValue()
        {
            string cachedHash;
            string path = HttpContext.Current.Server.MapPath(@"~\EFCache\MappingHashValue.txt");
            if (!File.Exists(path))
            {
                File.Create(path).Dispose();
            }
            using (var streamReader = new StreamReader(path, Encoding.UTF8))
            {
                cachedHash = streamReader.ReadToEnd();
            }
            return cachedHash;
        }

        public static void UpdateHashInCache(string hashValue)
        {
            string path = HttpContext.Current.Server.MapPath(@"~\EFCache\MappingHashValue.txt");
            using (var streamWriter = new StreamWriter(path, false))
            {
                streamWriter.Write(hashValue);
            }
        }

        private static void UpdateMappedViewInCache(Dictionary<EntitySetBase, DbMappingView> dict)
        {
            string path = HttpContext.Current.Server.MapPath(@"~\EFCache\MappingView.json");
            Dictionary<String, String> stringDict = new Dictionary<string, string>();
            foreach(var entry in dict)
            {

                stringDict[entry.Key.Name] = entry.Value.EntitySql.ToString();                
            }
            var json = new JavaScriptSerializer().Serialize(stringDict);
            using (var streamWriter = new StreamWriter(path, false))
            {
                streamWriter.Write(json);
            }
        }

        private static Dictionary<String, string> GetMappedViewFromCache()
        {
            string path = HttpContext.Current.Server.MapPath(@"~\EFCache\MappingView.json");
            var json = String.Empty; 
            using (var streamReader = new StreamReader(path, Encoding.UTF8))
            {
                json = streamReader.ReadToEnd();
            }
            Dictionary<String, string> mappedViewDict = new Dictionary<String, string>();
            if (!String.IsNullOrEmpty(json))
            {
                var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
                mappedViewDict = ser.Deserialize<Dictionary<String, string>>(json);
            }
            return mappedViewDict;
        }

        public static void CheckAndUpdateEFViewCache()
        {
            using (var ctx = new CascadeTranscationsDbContext(DBHelper.GetConnString()))
            {

                var objectContext = ((IObjectContextAdapter)ctx).ObjectContext;
                var mappingCollection = (StorageMappingItemCollection)objectContext.MetadataWorkspace
                                                                                    .GetItemCollection(DataSpace.CSSpace);
                string computedHashValue = mappingCollection.ComputeMappingHashValue();
                string currentHashValue = GetCachedHashValue();
                SetHashValue(computedHashValue);
                if (computedHashValue != currentHashValue)
                {
                    UpdateHashInCache(computedHashValue);
                    IList<EdmSchemaError> errors = new List<EdmSchemaError>();
                    Dictionary<EntitySetBase, DbMappingView> result = mappingCollection.GenerateViews(errors);
                    UpdateMappedViewInCache(result);
                }
            }
        }


    }

I have stored the hashvalue and mapping generated in a file and retrieved it in GetView() method.

I have exposed a public CheckAndUpdateEFViewCache() method which will generate the view mapping when called and store in file.

Step2: Call the CheckAndUpdateEFViewCache() from Global.asax file Application_Start() method.

Step3: Include assembly in the file where context is first called. [assembly: DbMappingViewCacheType(typeof(Models.Entities.MyDBContext), typeof(EFDbMappingViewCache))]

I am really not sure where this assembly line actually needs to go. There is no information on it in the link. There is a really good chance that Step3 might be where i have gone wrong.

Can someone help with the problem ?

The issue I had faced was because I already had a mapped file generated using EF Tools and it was registered. When the configuration I wrote attempted to register one more time, EF threw an error.

Further I want to add that Cached DB model store improved the performance several folds and I ended up using just that in my project. Link to Cached DB model store usage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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