服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#中Entity Framework常见报错汇总

C#中Entity Framework常见报错汇总

2022-02-13 15:13C#教程网 C#

给大家总结了C#中Entity Framework常见报错,以及处理这些错误的方法,希望能够为你提供到帮助。

以下小编整理的entity framework常见错误的汇总,大家如果还有不明白可以在下面留言区讨论。

1 实体属性配置为isrequired()对更新的影响

抛出异常类型dbentityvalidationexception

表结构:

C#中Entity Framework常见报错汇总

实体:

?
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
28
public class user
  {
    public int id { get; set; }
    /// <summary>
    /// 账号
    /// </summary>
    public string account { get; set; }
    /// <summary>
    /// 邮箱
    /// </summary>
    public string email { get; set; }
    /// <summary>
    /// 昵称
    /// </summary>
    public string nickname { get; set; }
    /// <summary>
    /// 头像
    /// </summary>
    public string avatarid { get; set; }
    /// <summary>
    /// 记录插入时间
    /// </summary>
    public datetime inserttime { get; set; }
    /// <summary>
    /// 记录修改时间
    /// </summary>
    public datetime updatetime { get; set; }
  }

实体配置:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 modelbuilder.entity<user>().property(u => u.account)
  .isrequired()
  .isunicode(false)
  .hasmaxlength(50);
modelbuilder.entity<user>().property(u => u.email)
  .isrequired()
  .isunicode(false)
  .hasmaxlength(100);
modelbuilder.entity<user>().property(u => u.nickname)
  .isunicode(false)
  .hasmaxlength(50);
modelbuilder.entity<user>().property(u => u.avatarid)
  .isoptional()
  .hasmaxlength(100);

customdbcontext继承自dbcontext

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[dbconfigurationtype(typeof(mysqlefconfiguration))]
  public class customdbcontext : dbcontext
  {
    public customdbcontext()
      : base("name=master")
    {
      
      this.configuration.lazyloadingenabled = false;
      //dropcreatedatabaseifmodelchanges
      //new dropcreatedatabasealways<customdbcontext>()
      database.setinitializer<customdbcontext>(null);
    }
 
    public dbset<user> users { get; set; }
 
    protected override void onmodelcreating(dbmodelbuilder modelbuilder)
    {
      base.onmodelcreating(modelbuilder);
      entityconfiguration.set(modelbuilder);
    }
}

更新操作:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
using (customdbcontext db = new customdbcontext())
{
          user user = new user
          {
            id = 1,
            email = "test@1622.com",
          };
          dbentityentry<user> entry = db.entry<user>(user);
          entry.state = entitystate.unchanged;
          entry.property(t => t.email).ismodified = true;
 
          int num = db.savechanges();
}

执行操作,报错信息如下:

C#中Entity Framework常见报错汇总

查看entityvalidationerrors,

只能看到{system.data.entity.validation.dbentityvalidationresult},没有更详细的信息。

如果将上述代码用try..catch包起来,如下写法:

?
1
2
3
4
5
6
7
8
9
10
11
try
{
//执行代码
}
catch (dbentityvalidationexception ex)
{
  var e = ex.entityvalidationerrors;
}
catch (exception ex)
{
}

一层一层地打开,看到真正导致异常的原因,看到下面的截图:

C#中Entity Framework常见报错汇总

分析实体配置发现,account属性被设置为isrequired,那么在更新实体的时候,即使不更新这个字段,也要给这个字段赋值,那么赋值后观察:

更新操作代码变为

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using (customdbcontext db = new customdbcontext())
{
  user user = new user
  {
    id = 1,
    email = "test@1622.com",
    account = "a"
  };
  dbentityentry<user> entry = db.entry<user>(user);
  entry.state = entitystate.unchanged;
  entry.property(t => t.email).ismodified = true;
 
  int num = db.savechanges();
}

经过上述调整后,更新成功。

那么换一个思路,将account属性被设置为isoptional()是不是也可以呢?

修改实体配置,将account属性设置按如下修改,并注掉上面的account = "a"

modelbuilder.entity<user>().property(u => u.account)

                .isoptional()

                .isunicode(false)

                .hasmaxlength(50);

执行测试,更改成功。

 

得出结论:在实体配置时,指定了为必选的字段,那么更新操作时,构造实例一定要对必选(isrequired())字段赋值。

上述测试中还有一个值得考虑的细节,构造user实例的时候,只对id,email进行了赋值,而没有对其他属性进行赋值,那么为什么会成功呢?那么必定是未进行任何设置的实体属性默认是isoptional()。这跟表结构中的字段类型设置为not null有无关联呢,从测试结果看就本类应用无必然联系。

总结:

a.实体配置中指定了实体属性为isrequired(),更新操作构造类的实例时必对此属性赋值。

b.不进行配置的实体属性默认为isoptional()

c.表结构中字段是否为not null对上述规则无影响。

2 更新报错:

an object with the same key already exists in the objectstatemanager. the objectstatemanager cannot track multiple objects with the same key.

异常类型:system.data.entity.infrastructure.dbupdateconcurrencyexception

实体属性配置如上例所示。

操作代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using (customdbcontext db = new customdbcontext())
{
  user user = new user
  {
    id = 1,
    email = "test@132.com",
  };
  dbentityentry<user> entry = db.entry<user>(user);
  entry.state = entitystate.unchanged;
  entry.property(t => t.email).ismodified = true;
 
  user user1 = new user
  {
    id = 1,
    email = "test@132.com",
  };
  dbentityentry<user> entry1 = db.entry<user>(user1);
  entry1.state = entitystate.unchanged;
  entry1.property(t => t.email).ismodified = true;
 
  int num = db.savechanges();
}

执行操作

C#中Entity Framework常见报错汇总

涉及到两次修改操作,两次操作构造了两个实例,但是实例的属性id有相同的值。

如果两次操作的是同一个实例,而不是不同的实例,那么不会抛出异常,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using (customdbcontext db = new customdbcontext())
{
  user user = new user
  {
    id = 1,
    email = "test@132.com",
  };
  dbentityentry<user> entry = db.entry<user>(user);
  entry.state = entitystate.unchanged;
  entry.property(t => t.email).ismodified = true;
 
  dbentityentry<user> entry1 = db.entry<user>(user);
  entry1.state = entitystate.unchanged;
  entry1.property(t => t.email).ismodified = true;
 
  int num = db.savechanges();
}

 

3 未给主键赋值或赋给主键一个不存在的值,抛出异常

system.data.entity.infrastructure.dbupdateconcurrencyexception

操作代码如下,其中id=1这条语句被注掉,id是主键:

?
1
2
3
4
5
6
7
8
9
10
11
12
using (customdbcontext db = new customdbcontext())
  {
    user user = new user
    {
      //id = 1,
      email = "test@132.com",
    };
    dbentityentry<user> entry = db.entry<user>(user);
    entry.state = entitystate.unchanged;
    entry.property(t => t.email).ismodified = true;
    int num = db.savechanges();
  }

运行上述代码,抛出异常信息如下,注意异常类型居然是system.data.entity.infrastructure.dbupdateconcurrencyexception,看上去像是并发问题,但实际却不是!

message:

store update, insert, or delete statement affected an unexpected number of rows (0). entities may have been modified or deleted since entities were loaded. refresh objectstatemanager entries.

C#中Entity Framework常见报错汇总

赋给主键一个不存在的值,令id=4(在数据库表中不存在id为4的一条记录)抛出的异常与上面的相同。

4 字段超长抛出异常:system.data.entity.validation.dbentityvalidationexception

表中nickname 字段定义为50个字符,现在赋值超过50。

操作代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
using (customdbcontext db = new customdbcontext())
        {
          user user = new user
          {
            id = 4,
            email = "test@132.com",
            nickname = "testupdateerrortestupdateerrortestupdateerrortestupdateerrortestupdateerrortestupdateerrortestupdateerrortestupdateerrortestupdateerrortestupdateerrortestupdateerror"
          };
          dbentityentry<user> entry = db.entry<user>(user);
          entry.state = entitystate.unchanged;
          entry.property(t => t.email).ismodified = true;
          int num = db.savechanges();
        }

运行程序报错:C#中Entity Framework常见报错汇总

一层一层点开,查看具体原因:C#中Entity Framework常见报错汇总

 

原文链接:https://www.cnblogs.com/hdwgxz/p/7897031.html

延伸 · 阅读

精彩推荐
  • C#聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题,新手速来围观,一个通俗易懂的例子帮助大家更好的理解C#接口问题,感兴趣的小伙伴们可以参考一下...

    zenkey7072021-12-03
  • C#C# 后台处理图片的几种方法

    C# 后台处理图片的几种方法

    本篇文章主要介绍了C# 后台处理图片的几种方法,非常具有实用价值,需要的朋友可以参考下。...

    IT小伙儿10162021-12-08
  • C#Unity3D UGUI实现缩放循环拖动卡牌展示效果

    Unity3D UGUI实现缩放循环拖动卡牌展示效果

    这篇文章主要为大家详细介绍了Unity3D UGUI实现缩放循环拖动展示卡牌效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    诗远3662022-03-11
  • C#c#学习之30分钟学会XAML

    c#学习之30分钟学会XAML

    一个界面程序的核心,无疑就是界面和后台代码,而xaml就是微软为构建应用程序界面而创建的一种描述性语言,也就是说,这东西是搞界面的...

    C#教程网8812021-12-10
  • C#浅谈C# winForm 窗体闪烁的问题

    浅谈C# winForm 窗体闪烁的问题

    下面小编就为大家带来一篇浅谈C# winForm 窗体闪烁的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网7962021-12-21
  • C#C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    这篇文章主要介绍了C#实现的文件操作封装类,结合完整实例形式分析了C#封装文件的删除,移动,复制,重命名等操作相关实现技巧,需要的朋友可以参考下...

    Rising_Sun3892021-12-28
  • C#C#直线的最小二乘法线性回归运算实例

    C#直线的最小二乘法线性回归运算实例

    这篇文章主要介绍了C#直线的最小二乘法线性回归运算方法,实例分析了给定一组点,用最小二乘法进行线性回归运算的实现技巧,具有一定参考借鉴价值,需要...

    北风其凉8912021-10-18
  • C#C#基础之泛型

    C#基础之泛型

    泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。接下来通过本文给大家介绍c#基础之泛型,感兴趣的朋友一起学习吧...

    方小白7732021-12-03