全球彩票平台_全球彩票注册平台|官网下载地址

热门关键词: 全球彩票平台,全球彩票注册平台,全球彩官网下载地址

全球彩票注册平台高级场景,Update总是失败及其

vs报错找不到错在哪个地方!Validation failed for one or more entities,validationentities

明天在拍卖Entity Framework修改数据库时,报错:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

实在是找不到原因

全球彩票注册平台 1

貌似的谬误用的是try catch(Exception ex) 来看错误,可是这种气象找不到错误。

改用了一种System.Data.Entity.Validation.DbEntityValidationException的查看错误机制

try

{

// 写数据库

}

catch (DbEntityValidationException dbEx)

{

}

入选dbex右键“增加监视” 查看原因是二个字段的多寡格式错误(末尾有空格)

这种方法查看错误某种情状下比exception要好管理局地。

failed for one or more entities,validationentities 前日在拍卖Entity Framework修改数据库时,报错: Validation failed for...

诚如的失实用的是try catch(Exception ex) 来看错误,不过这种情形找不到不当。

实际是找不到原因

出处:

  假如大家想利用SQL取代LINQ。而且必要重临非实体对象,大家就须要运用Database.SqlQuery方法。

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

改用了一种System.Data.Entity.Validation.DbEntityValidationException的查阅错误机制

至于Entity Framework中的Attached报错的一应俱全实施方案终极版

前发布过一篇作品题为《有关Entity Framework中的Attached报错的周详施工方案》,那篇文章确实能消除单个实体在扩充翻新、删除时Attached的报错,注意自己这边说的单个实体,指的是要更新或删除的实业不带有其余实体(比方导航属性就隐含别的实体),也正是回顾POCO对象;但借使不是吗?那么那篇小说里的办法在早晚水准上不起效率了,仍会报错,作者起来也想不清楚,明明透过IsAttached函数判别要更新的实体并未Attached,但进展Attaching时但依然报错说有同样Key,开头还认为是MS的BUG,后通过反复频仍调试开采,报错是对的,因为他报的错却非本人眼下要翻新的实业,而是该实体中提到的实业,代码与示范报错如下:(仅是身先士卒代码)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class A
{
   public string a{get;set;}
   public string b{get;set;}
   public string c{get;set;}
   public virtual B b{get;set;}
}
 
public class B
{
   public string x{get;set;}
   public string y{get;set;}
   public string z{get;set;}
}
 
var a1= dbContext.Set<A>().Single();
a1.a="test1";
dbContext.SaveChanges();
 
dbContext.Detach(a1);//从缓存中移除a1实体;
 
 
var a2= dbContext.Set<A>().AsNoTracking().Single();
a2.a="test2";
 dbContext.Set<A>().Attach(a2); //报错,说B相同的KEY已经有Attached
dbContext.Entry(entity).State = EntityState.Modified;
dbContext.SaveChanges();

本着那一个报错,作者在想,为什么查询实体A的时候能并且涉嫌查询实体B并都相同的时间Attached到内部存款和储蓄器中,而当自身施行Detach实体A时,却未能关联Detach实体B,难点来自就在那边,知道这一个原因了,现在正是要缓和那些主题素材,怎么着消除吗?既然知道是Detach实体不周密产生的,那么小编只需求获得到近来DbContext上下文对象中存活的持有已Attached实体,在实行完相应的CRUD时,再整体各样Detach掉就可以,建设方案代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/// <summary>
/// 清空DB上下文中所有缓存的实体对象
/// </summary>
private void DetachedAllEntities()
{
    var objectContext = ((IObjectContextAdapter)this.baseContext).ObjectContext;
    List<ObjectStateEntry> entries = new List<ObjectStateEntry>();
    var states = new[] { EntityState.Added, EntityState.Deleted, EntityState.Modified, EntityState.Unchanged };
    foreach (var state in states)
    {
        entries.AddRange(objectContext.ObjectStateManager.GetObjectStateEntries(state));
    }
 
    foreach (var item in entries)
    {
        objectContext.Detach(item.Entity);
    }
}
 
 
public void Commit()  //封装的统一提交方法
{
    this.baseContext.SaveChanges();
    this.DetachedAllEntities();//执行清除
}

在应用的时候合作在此以前那篇作品的IsAttached函数就能够健全消除全数的Attached报错难题了!

=======================================================================================

在Repository方式中,小编的Update方法总是力所不及立异实体,这一个可怜消沉,Update方法如下:

   1:  public virtual void Update(T entity)

   2:          {

   3:              try

   4:              {

   5:                  if (entity == null) throw new ArgumentNullException("实体类为空");

   6:                  Context.Entry(entity).State = EntityState.Modified;

   7:                  //Context.SaveChanges();

   8:              }

   9:              catch (DbEntityValidationException dbex)

  10:              {

  11:                  var msg = string.Empty;

  12:                  foreach (var validationErrors in dbex.EntityValidationErrors)

  13:                      foreach (var validateionError in validationErrors.ValidationErrors)

  14:                          msg  = string.Format("Property:{0} Error:{1}", validateionError.PropertyName, validateionError.ErrorMessage);

  15:   

  16:                  var fail = new Exception(msg, dbex);

  17:                  throw fail;

  18:              }

  19:          }

全球彩票注册平台, 

看上去是从未任何难题的代码,一旦有实体更新的时候,总会冒出如下的不当提醒:

Attaching an entity of type 'TinyFrame.Data.DomainModel.t_user_application' failed because another entity of the same type already has the same primary keyvalue. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

看字面意思,好疑似自家的EntityState设置不正确导致的,即使自身尝试过重新恢复设置五次EntityState,不过还是无法缓和本身的难题。

然后实际找不出原因,就使用重大字 “ EF Repository Update ”在谷歌(Google)上边搜罗,果然找到一篇小说:Advanced Entity Framework 6 Scenarios for an MVC 5 Web Application (12 of 12),当中有一段话,建议了难点的所在:

 

This happened because of the following sequence of events:

 

    The Edit method calls the ValidateOneAdministratorAssignmentPerInstructor method, which retrieves all departments that have Kim Abercrombie as their administrator. That causes the English department to be read. As a result of this read operation, the English department entity that was read from the database is now being tracked by the database context.

    The Edit method tries to set the Modified flag on the English department entity created by the MVC model binder, which implicitly causes the context to try to attach that entity. But the context can't attach the entry created by the model binder because the context is already tracking an entity for the English department.

 

One solution to this problem is to keep the context from tracking in-memory department entities retrieved by the validation query. There's no disadvantage to doing this, because you won't be updating this entity or reading it again in a way that would benefit from it being cached in memory.

 

主题素材的来头如下:

在Context对象中,已经hold住了一个内需操作的靶子,当我们把EntityState修改成modified的时候,Context会再一次去加载那一个操作对象,不过这么加载是不能成功的,因为脚下已经存在多个目的了,再加载会产生重复,然后抛出失利的失实。

解决方法非常粗略,就是在呈现列表的时候,利用AsNoTracking将Hold住的对象释放掉就能够。大家修改代码如下:

 

 

   1:   public virtual T Get(Expression<Func<T, bool>> where)

   2:          {

   3:              return Dbset.Where(where).AsNoTracking().FirstOrDefault<T>();

   4:          }

   5:   

   6:          public virtual IQueryable<T> GetMany(Expression<Func<T, bool>> where)

   7:          {

   8:              return Dbset.Where(where).AsNoTracking();

   9:          }

 

 

下一场提交,OK,难点一蹴而就。

 

=============================Update 2014.09.19======================

看样子商议中有恋人就算依据上述办法,可是依然不能消除这一主题材料。原因是在Context中还保留有眼下实体的别本所致,这里只要大家将实体别本从内部存储器中全然移除,就足以了。

全球彩票注册平台 2

   //用于监测Context中的Entity是否存在,如果存在,将其Detach,防止出现问题。
        private Boolean RemoveHoldingEntityInContext(T entity)
        {
            var objContext = ((IObjectContextAdapter)_context).ObjectContext;
            var objSet = objContext.CreateObjectSet<T>();
            var entityKey = objContext.CreateEntityKey(objSet.EntitySet.Name, entity);

            Object foundEntity;
            var exists = objContext.TryGetObjectByKey(entityKey, out foundEntity);

            if (exists)
            {
                objContext.Detach(foundEntity);
            }

            return (exists);
        }

全球彩票注册平台 3

下一场在Repository中,在张开翻新和删除在此之前,运营一下就能够:

全球彩票注册平台 4

  public T Remove(T entity)
        {
            try
            {
                RemoveHoldingEntityInContext(entity);

                _context.DbSet<T>().Attach(entity);
                return _context.DbSet<T>().Remove(entity);
            }
            catch (DbEntityValidationException dbex)
            {
                var msg = string.Empty;
                foreach (var validationErrors in dbex.EntityValidationErrors)
                    foreach (var validateionError in validationErrors.ValidationErrors)
                        msg  = string.Format("属性:{0} 错误:{1}", validateionError.PropertyName, validateionError.ErrorMessage);
                var fail = new Exception(msg, dbex);
                throw fail;
            }
        }

        public T Update(T entity)
        {
            try
            {
                RemoveHoldingEntityInContext(entity);

                var updated = _context.DbSet<T>().Attach(entity);
                _context.DbContext.Entry(entity).State = EntityState.Modified;
                return updated;
            }
            catch (DbEntityValidationException dbex)
            {
                var msg = string.Empty;
                foreach (var validationErrors in dbex.EntityValidationErrors)
                    foreach (var validateionError in validationErrors.ValidationErrors)
                        msg  = string.Format("属性:{0} 错误:{1}", validateionError.PropertyName, validateionError.ErrorMessage);
                var fail = new Exception(msg, dbex);
                throw fail;
            }
        }

全球彩票注册平台 5

 

参照博文:

 

全球彩票注册平台 6

前些天在拍卖Entity Framework修改数据库时,报错:

try

{

// 写数据库

}

catch (DbEntityValidationException dbEx)

{

}

  当叁个数据库上下文找寻到表中的行数据会为他们成立实体对象,私下认可意况下它会一向追踪内部存款和储蓄器中的实体是或不是和数据库中的数据保持一致。内部存款和储蓄器中的数目作为缓存和换代实体时选用。这种缓存在web应用程序中常见是从没有过要求的,因为上下文实例平日是短距离赛跑的(每趟须要都会新建和销毁二个上下文实例),并且普通上下文读取的实例在该实例再度被利用前就早就灭绝 。

改用了一种System.Data.Entity.Validation.DbEntityValidationException的查看错误机制

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

SELECT 
    [Project1].[CourseID] AS [CourseID], 
    [Project1].[Title] AS [Title], 
    [Project1].[Credits] AS [Credits], 
    [Project1].[DepartmentID] AS [DepartmentID], 
    [Project1].[DepartmentID1] AS [DepartmentID1], 
    [Project1].[Name] AS [Name], 
    [Project1].[Budget] AS [Budget], 
    [Project1].[StartDate] AS [StartDate], 
    [Project1].[InstructorID] AS [InstructorID], 
    [Project1].[RowVersion] AS [RowVersion]
    FROM ( SELECT 
        [Extent1].[CourseID] AS [CourseID], 
        [Extent1].[Title] AS [Title], 
        [Extent1].[Credits] AS [Credits], 
        [Extent1].[DepartmentID] AS [DepartmentID], 
        [Extent2].[DepartmentID] AS [DepartmentID1], 
        [Extent2].[Name] AS [Name], 
        [Extent2].[Budget] AS [Budget], 
        [Extent2].[StartDate] AS [StartDate], 
        [Extent2].[InstructorID] AS [InstructorID], 
        [Extent2].[RowVersion] AS [RowVersion]
        FROM  [dbo].[Course] AS [Extent1]
        INNER JOIN [dbo].[Department] AS [Extent2] ON [Extent1].[DepartmentID] = [Extent2].[DepartmentID]
        WHERE @p__linq__0 IS NULL OR [Extent1].[DepartmentID] = @p__linq__1
    )  AS [Project1]
    ORDER BY [Project1].[CourseID] ASC

这种格局查看错误某种景况下比exception要好处理局地。

诚如的荒唐用的是try catch(Exception ex) 来看错误,不过这种情景找不到不当。

HTTP 500.19 error

Error Message:

HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

Solution

其一荒唐的二个缘故是涸泽而渔方案有四个别本,而且那个别本使用同一的端口号。常常我们得以由此关闭全数的Visual Studio,然后重启项目来化解此难点。若是上述办法不奏效,就改动端口号。右键项目,点击properties,选拔Web标签在Project Url修改端口号。

入选dbex右键“加多监视” 查看原因是二个字段的数量格式错误(末尾有空格)

今天在拍卖Entity Framework修改数据库时,报错:

  以前我们在About页面创立了几个student计算报表,展现每一个enrollment date的student数量。LINQ代码如下:

全球彩票注册平台 7

全球彩票注册平台 8

  越来越多关于原生SQL查询新闻请查看:Raw SQL Queries。

实际是找不到原因

这种措施查看错误某种意况下比exception要好管理局地。

8.EF源码

try

{

// 写数据库

}

catch (DbEntityValidationException dbEx)

{

}

入选dbex右键“添加监视” 查看原因是八个字段的数码格式错误(末尾有空格)

全球彩票注册平台 9

  Entity Framework Power Tools是Visual Studio内置的用来创制本课程展现的数据模型图。该工具同样有着任何职能,比如依据已经存在的数据库的表发生实体类,那样就足以应用Code First。安装此工具后,上下文菜单会并发一些任何的选项。譬如,当我们在Solution Explorer的内外文类中右键,会并发发生图表选项。当大家选取Code First时,大家不能改变图表中的数据模型,不过大家能够移动它们的位置,让它们变得轻便通晓。

  就算EF是开源的,可是它是微软完全帮衬的成品。微软的EF团队调节接受什么进献的代码并对持有的更改进行测量试验以保障各个发行版本的材质。

public ActionResult Index(int? SelectedDepartment)
{
    var departments = db.Departments.OrderBy(q => q.Name).ToList();
    ViewBag.SelectedDepartment = new SelectList(departments, "DepartmentID", "Name", SelectedDepartment);
    int departmentID = SelectedDepartment.GetValueOrDefault();

    IQueryable<Course> courses = db.Courses
        .Where(c => !SelectedDepartment.HasValue || c.DepartmentID == departmentID)
        .OrderBy(d => d.CourseID)
        .Include(d => d.Department);
    var sql = courses.ToString();
    return View(courses.ToList());
}

Error locating SQL Server instance

Error Message:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

Solution

查阅连接字符串。假若手动删除了数据库,则修改连接字符串的多少库名。

 

全球彩票注册平台 10

  越来越多关于落实仓库储存和工作单元形式消息请参见:the Entity Framework 5 version of this tutorial series。越来越多关于在EF6中贯彻TDD消息请参见:

1.2.调用查询再次来到别的品类的目的:

全球彩票注册平台 11

  修改HomeController.csAbout方法:

本文由全球彩票平台发布于全球彩票注册平台编程,转载请注明出处:全球彩票注册平台高级场景,Update总是失败及其

TAG标签: 全球彩票平台
Ctrl+D 将本页面保存为书签,全面了解最新资讯,方便快捷。