gpt4 book ai didi

c# - EF(entity framework) "using"statement 和 "try catch"withing each

转载 作者:太空宇宙 更新时间:2023-11-03 13:38:08 25 4
gpt4 key购买 nike

这些使用/try-catch block 的方式有什么区别吗?

首先:

public bool Insert(SomeEntity entity)
{
bool result = false;

try
{
using (var db = new MyEntities())
{
db.AddToSomeEntity(entity);
db.SaveChanges();

result = true;
}
}
catch (Exception e)
{
//
}
return result;
}

第二个:

public bool Insert(SomeEntity entity)
{
bool result = false;
using (var db = new MyEntities())
{
try
{
db.AddToSomeEntity (entity);
db.SaveChanges();
result = true;
}
catch (Exception e)
{
//
}
}

return result;
}

它会影响性能吗?

This string was added in order to satisfy SO submit validation rule.

最佳答案

我不认为它违反了任何规则你想在什么时候将你的上下文发送到垃圾收集我建议使用第二种方法因为它更具体并且你将在你的函数被发送时将对象发送到垃圾收集完全执行,否则您可能会在尝试使用不再可用的上下文时遇到异常

关于c# - EF(entity framework) "using"statement 和 "try catch"withing each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18039980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com