欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中Entity Framework常见报错汇总

程序员文章站 2023-12-18 23:33:10
以下小编整理的entity framework常见错误的汇总,大家如果还有不明白可以在下面留言区讨论。 1 实体属性配置为isrequired()对更新的影响 抛出异常...

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

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

抛出异常类型dbentityvalidationexception

表结构:

C#中Entity Framework常见报错汇总

实体:

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; }
  }

实体配置:

       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

[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);
    }
}

更新操作:

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包起来,如下写法:

try
{
//执行代码
}
catch (dbentityvalidationexception ex)
{
  var e = ex.entityvalidationerrors;
}
catch (exception ex)
{
}

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

C#中Entity Framework常见报错汇总

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

更新操作代码变为

 

        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

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

操作代码:

        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有相同的值。

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

        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是主键:

      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。

操作代码如下:

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常见报错汇总

上一篇:

下一篇: