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

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#WPF 自定义雷达图开发实例教程

    WPF 自定义雷达图开发实例教程

    这篇文章主要介绍了WPF 自定义雷达图开发实例教程,本文介绍的非常详细,具有参考借鉴价值,需要的朋友可以参考下...

    WinterFish13112021-12-06
  • C#Unity3D实现虚拟按钮控制人物移动效果

    Unity3D实现虚拟按钮控制人物移动效果

    这篇文章主要为大家详细介绍了Unity3D实现虚拟按钮控制人物移动效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一...

    shenqingyu060520232410972022-03-11
  • C#C#设计模式之Visitor访问者模式解决长隆欢乐世界问题实例

    C#设计模式之Visitor访问者模式解决长隆欢乐世界问题实例

    这篇文章主要介绍了C#设计模式之Visitor访问者模式解决长隆欢乐世界问题,简单描述了访问者模式的定义并结合具体实例形式分析了C#使用访问者模式解决长...

    GhostRider9502022-01-21
  • C#深入解析C#中的交错数组与隐式类型的数组

    深入解析C#中的交错数组与隐式类型的数组

    这篇文章主要介绍了深入解析C#中的交错数组与隐式类型的数组,隐式类型的数组通常与匿名类型以及对象初始值设定项和集合初始值设定项一起使用,需要的...

    C#教程网6172021-11-09
  • C#C#通过KD树进行距离最近点的查找

    C#通过KD树进行距离最近点的查找

    这篇文章主要为大家详细介绍了C#通过KD树进行距离最近点的查找,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    帆帆帆6112022-01-22
  • C#C#实现XML文件读取

    C#实现XML文件读取

    这篇文章主要为大家详细介绍了C#实现XML文件读取的相关代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    Just_for_Myself6702022-02-22
  • C#C# 实现对PPT文档加密、解密及重置密码的操作方法

    C# 实现对PPT文档加密、解密及重置密码的操作方法

    这篇文章主要介绍了C# 实现对PPT文档加密、解密及重置密码的操作方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下...

    E-iceblue5012022-02-12
  • C#C#裁剪,缩放,清晰度,水印处理操作示例

    C#裁剪,缩放,清晰度,水印处理操作示例

    这篇文章主要为大家详细介绍了C#裁剪,缩放,清晰度,水印处理操作示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    吴 剑8332021-12-08