c# – CA1001 Visual Studio 2012代码分析警告.这是什么意思?

前端之家收集整理的这篇文章主要介绍了c# – CA1001 Visual Studio 2012代码分析警告.这是什么意思?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
它并不重要,但我想弄清楚它告诉我什么,这是一个合理的警告吗?有人可以用简单的术语解释这个错误吗?

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

上下文是轻量级的,因此每次创建它们都没有太大的代价.此外,您不必担心消费者会通知您处理上下文,并且如果多次使用该类的一个实例,则内存中没有很多内置更改.

原文链接:https://www.f2er.com/csharp/91805.html

猜你在找的C#相关文章