实体框架错误ReflectionTypeLoadException

时间:2014-01-24 19:00:25

标签: c# asp.net-mvc entity-framework asp.net-mvc-4 dbcontext

当我尝试在数据库中保存数据时,我收到此错误:

无法加载一个或多个请求的类型。检索LoaderExceptions属性以获取更多信息。

使用EF对象的所有操作都会发生错误,例如当我执行此操作时(返回步骤):

public User GetUser(int userId)
        {
            try
            {
                return _db.Users.FirstOrDefault(x => x.UserId == userId && !x.IsDeleted);
            }
            catch (Exception ex)
            {
                this._lastError = ex.Message;
                return null;
            }
        }

或者这个(在AddObject步骤上):

   public bool AddAdditionalUserInfo(int userId, string firstName, string lastName, string emailAddress)
        {
            try
            {
                UserInfo userInfo = new UserInfo();
                userInfo.UserId = userId;
                userInfo.FirstName = firstName;
                userInfo.LastName = lastName;
                userInfo.EmailAddress = emailAddress;
                userInfo.UserInfoId = 0;
                _db.UserInfoes.AddObject(userInfo);                
                _db.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                this._lastError = ex.Message;
                return false;
            }
        }

1 个答案:

答案 0 :(得分:3)

好的,所以当你收到这条消息时,错误会有所不同。我的问题是我安装了EF 5,而我引用的另一个项目有4.4并且存在冲突。 在异常块中执行此代码将帮助您获得确切的消息:

using System.IO;
using System.Reflection;

try
{
    //The code that causes the error goes here.
}
catch (ReflectionTypeLoadException ex)
{
    StringBuilder sb = new StringBuilder();
    foreach (Exception exSub in ex.LoaderExceptions)
    {
        sb.AppendLine(exSub.Message);
        if (exSub is FileNotFoundException)
        {
            FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
            if(!string.IsNullOrEmpty(exFileNotFound.FusionLog))
            {
                sb.AppendLine("Fusion Log:");
                sb.AppendLine(exFileNotFound.FusionLog);
            }
        }
        sb.AppendLine();
    }
    string errorMessage = sb.ToString();
    //Display or log the error based on your application.
}

最初写在这篇文章中:Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'