它不是那么重要,但我想弄清楚它在告诉我什么,它是否是一个合理的警告?有人可以用简单的术语为我解释这个错误吗?
CA1001 Types that own disposable fields should be disposable
Implement IDisposable on 'MemVoteManager' because it creates members of the following IDisposable types: 'CongressDBEntities'. If 'MemVoteManager' has previously shipped, adding new members that implement IDisposable to this type is considered a breaking change to existing consumers.
public class MemVoteManager : AbstractDataManager, IMemVoteManager
{
private CongressDBEntities context = new CongressDBEntities();
public int AddMemVote(tMemVoteScore mvs)
{
//Insert Model
context.tMemVoteScores.Add(mvs);
context.SaveChanges();
int newPK = mvs.MemVoteScoresID;
//Update funky column ID with PK as well
var memVoteItem = (from m in context.tMemVoteScores
where m.MemVoteScoresID == newPK
select m).SingleOrDefault();
memVoteItem.ID = memVoteItem.MemVoteScoresID;
context.SaveChanges();
return newPK;
}
最佳答案
您可以实现IDisposable
,这样当消费者使用完您的类时上下文将被释放,但最好不要让上下文成为类。只需在需要时创建它并在完成后处理它:
public int AddMemVote(tMemVoteScore mvs)
{
//Insert Model
using(CongressDBEntities context = new CongressDBEntities())
{
context.tMemVoteScores.Add(mvs);
context.SaveChanges();
int newPK = mvs.MemVoteScoresID;
//Update funky column ID with PK as well
var memVoteItem = (from m in context.tMemVoteScores
where m.MemVoteScoresID == newPK
select m).SingleOrDefault();
memVoteItem.ID = memVoteItem.MemVoteScoresID;
context.SaveChanges();
}
return newPK;
}
上下文是轻量级的,因此每次创建它们不会造成很大的损失。此外,您不必担心消费者会通知您处理上下文,并且如果类的一个实例被多次使用,您也不会在内存中有很多内置更改。
关于c# - CA1001 Visual Studio 2012 代码分析警告。这是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15164592/