【问题标题】:type used in a using statement must be implicity convertible to system.Idisposableusing 语句中使用的类型必须可隐式转换为 system.Idisposable
【发布时间】:2014-08-05 13:06:18
【问题描述】:

开始了一个新的 mvc4 项目。使用 MVC 控制器模板创建 'Orders' 模型的读/写操作。向我的数据库添加了一个新的实体框架连接,并尝试使用新订单对其进行更新。

[HttpPost]
    public ActionResult Create(Orders orders)
    {
        try
        {

            //type used in a using statement must be implicity convertible to system.Idisposable
            using (BuyABicycleEntities db = new BuyABicycleEntities())
            {
                Order NewOrder = new Order();
                NewOrder.BicycleColour = orders.BicycleColour;
                NewOrder.BicycleModel = orders.BicycleModel;
                NewOrder.BicycleSize = orders.BicycleSize;
                NewOrder.CustomerAddress = orders.CustomerAddress;
                NewOrder.CustomerEmail = orders.CustomerEmail;
                NewOrder.CustomerName = orders.CustomerName;
                NewOrder.CustomerPhoneNumber = orders.CustomerPhoneNumber;

                //entiry framework new item
                //db.Orders.(NewOrder);
                db.SaveChanges();

            }

            return View(orders);
        }
        catch (Exception ex)
        {
            //Show Message("Error in Orders - " + ex.Message);

        }
    }

但是 using 语句正在标记错误:

在 using 语句中使用的类型必须可以隐式转换为 system.Idisposable

所以我必须实现idisposable?,每次我想更新数据库时都必须这样做吗?通过stackoverflow搜索了很多类似的Q,但仍然不确定如何处理我的?请指教。谢谢

    // ------------------------------------------------------------------------------
// DO NOT MODIFY THIS CLASS - AutoGenerated Code
//    Any changes made to this code will be lost the next time this 
//    code is regenerated.
// 
//    Generated at: 05/08/2014 14:16:31
//    DevForce version: 6.1.7.0
//    Template version: 2.1.4
// ------------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using IbEm   = IdeaBlade.EntityModel;
using IbCore = IdeaBlade.Core;
using IbVal  = IdeaBlade.Validation;

[module: IbCore.IdeaBladeLicense("5w+U/Qneh0KYrGDaCOhKKqJpzM0BhW5i7ky77IZpGawLem2DQ5JuP6W8fhhcpF/x")]

namespace MvcApplication18 { 

  #region BuyABicycleEntities

  /// <summary>
  /// The domain-specific EntityManager for your domain model.
  /// </summary>
  public partial class BuyABicycleEntities : IbEm.EntityManager {

    #region Constructors

    /// <summary>See <see cref="M:IbEm.EntityManager.#ctor(bool, string, IbEm.EntityServiceOption, string)"/>. </summary>
    public BuyABicycleEntities(bool shouldConnect=true, string dataSourceExtension=null, IbEm.EntityServiceOption entityServiceOption=IbEm.EntityServiceOption.UseDefaultService, string compositionContextName=null) : base(shouldConnect, dataSourceExtension, entityServiceOption, compositionContextName) {}

    /// <summary>See <see cref="M:IbEm.EntityManager.#ctor(IbEm.EntityManagerContext)"/>. </summary>
    public BuyABicycleEntities(IbEm.EntityManagerContext entityManagerContext) : base(entityManagerContext) {}

    /// <summary>See <see cref="M:IbEm.EntityManager.#ctor(IbEm.EntityManager, bool, string, IbEm.EntityServiceOption, string)"/>. </summary>
    public BuyABicycleEntities(IbEm.EntityManager entityManager, bool shouldConnect, string dataSourceExtension=null, IbEm.EntityServiceOption entityServiceOption=IbEm.EntityServiceOption.UseDefaultService, string compositionContextName=null) : base(entityManager, shouldConnect, dataSourceExtension, entityServiceOption, compositionContextName) {}

    /// <summary>See <see cref="M:IbEm.EntityManager.#ctor(IbEm.EntityManager, IbEm.EntityManagerContext)"/>. </summary>
    public BuyABicycleEntities(IbEm.EntityManager entityManager, IbEm.EntityManagerContext entityManagerContext=null) : base(entityManager, entityManagerContext) {}

    static BuyABicycleEntities() {
      IbEm.EntityRelation.InitializeEntityRelations(System.Reflection.Assembly.GetExecutingAssembly());
    }
    #endregion Constructors

    #region EntityQueries

    /// <summary>Gets the <see cref="T:IbEm.EntityQuery"/> associated with the given EntitySet name. </summary>
    public IbEm.EntityQuery<BicycleModel> BicycleModels {
      get { return new IbEm.EntityQuery<BicycleModel>("BicycleModels", this); }
    }

    /// <summary>Gets the <see cref="T:IbEm.EntityQuery"/> associated with the given EntitySet name. </summary>
    public IbEm.EntityQuery<Customer> Customers {
      get { return new IbEm.EntityQuery<Customer>("Customers", this); }
    }

    /// <summary>Gets the <see cref="T:IbEm.EntityQuery"/> associated with the given EntitySet name. </summary>
    public IbEm.EntityQuery<Order> Orders {
      get { return new IbEm.EntityQuery<Order>("Orders", this); }
    }
    #endregion EntityQueries
  }
  #endregion BuyABicycleEntities

  #region BicycleModel class

  /// <summary>The auto-generated BicycleModel class. </summary>
  [DataContract(IsReference=true)]
  [IbEm.DataSourceKeyName(@"BuyABicycleEntities")]
  [IbEm.DefaultEntitySetName(@"BuyABicycleEntities.BicycleModels")]
  public partial class BicycleModel : IbEm.Entity {

    /// <summary>Returns the property path for the given expression. </summary>
    /// <example>
    /// Usage:
    /// <code>
    ///    var r = Employee.PathFor(e => e.Manager.City); // returns "Manager.City"
    /// </code>
    /// </example>
    public static string PathFor(System.Linq.Expressions.Expression<System.Func<BicycleModel, object>> expr) {
      return IbCore.PropertyPath.For<BicycleModel>(expr);
    }

    #region Data Properties

    /// <summary>Gets or sets the Id. </summary>
    [Key]
    [DataMember]
    [Bindable(true, BindingDirection.TwoWay)]
    [Editable(true)]
    [Display(Name="Id", AutoGenerateField=true)]
    [IbVal.RequiredValueVerifier( ErrorMessageResourceName="BicycleModel_Id")]
    public int Id {
      get { return PropertyMetadata.Id.GetValue(this); }
      set { PropertyMetadata.Id.SetValue(this, value); }
    }

    /// <summary>Gets or sets the ModelName. </summary>
    [DataMember]
    [Bindable(true, BindingDirection.TwoWay)]
    [Editable(true)]
    [Display(Name="ModelName", AutoGenerateField=true)]
    [IbVal.StringLengthVerifier(MaxValue=50, IsRequired=true, ErrorMessageResourceName="BicycleModel_ModelName")]
    public string ModelName {
      get { return PropertyMetadata.ModelName.GetValue(this); }
      set { PropertyMetadata.ModelName.SetValue(this, value); }
    }
    #endregion Data Properties

    #region Navigation properties
    #endregion Navigation properties

    #region EntityProperty definitions
    public partial class PropertyMetadata {

      /// Explicit static constructor ensures static fields are initialized.
      static PropertyMetadata() {}

      /// <summary>The Id <see cref="T:IbEm.DataEntityProperty"/>. </summary>
      public static readonly IbEm.DataEntityProperty<BicycleModel, int> Id = new IbEm.DataEntityProperty<BicycleModel, int>("Id", false, true, IbEm.ConcurrencyStrategy.None, true, null);

      /// <summary>The ModelName <see cref="T:IbEm.DataEntityProperty"/>. </summary>
      public static readonly IbEm.DataEntityProperty<BicycleModel, string> ModelName = new IbEm.DataEntityProperty<BicycleModel, string>("ModelName", false, false, IbEm.ConcurrencyStrategy.None, false, null);
    }
    #endregion EntityProperty definitions

    #region EntityPropertyNames
    public new partial class EntityPropertyNames : IbEm.Entity.EntityPropertyNames {
      public const String Id = "Id";
      public const String ModelName = "ModelName";
    }
    #endregion EntityPropertyNames
  }
  #endregion BicycleModel class

  #region Customer class

  /// <summary>The auto-generated Customer class. </summary>
  [DataContract(IsReference=true)]
  [IbEm.DataSourceKeyName(@"BuyABicycleEntities")]
  [IbEm.DefaultEntitySetName(@"BuyABicycleEntities.Customers")]
  public partial class Customer : IbEm.Entity {

    /// <summary>Returns the property path for the given expression. </summary>
    /// <example>
    /// Usage:
    /// <code>
    ///    var r = Employee.PathFor(e => e.Manager.City); // returns "Manager.City"
    /// </code>
    /// </example>
    public static string PathFor(System.Linq.Expressions.Expression<System.Func<Customer, object>> expr) {
      return IbCore.PropertyPath.For<Customer>(expr);
    }

    #region Data Properties

    /// <summary>Gets or sets the Id. </summary>
    [Key]
    [DataMember]
    [Bindable(true, BindingDirection.TwoWay)]
    [Editable(true)]
    [Display(Name="Id", AutoGenerateField=true)]
    [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Customer_Id")]
    public int Id {
      get { return PropertyMetadata.Id.GetValue(this); }
      set { PropertyMetadata.Id.SetValue(this, value); }
    }

    /// <summary>Gets or sets the CustomerName. </summary>
    [DataMember]
    [Bindable(true, BindingDirection.TwoWay)]
    [Editable(true)]
    [Display(Name="CustomerName", AutoGenerateField=true)]
    [IbVal.StringLengthVerifier(MaxValue=50, IsRequired=true, ErrorMessageResourceName="Customer_CustomerName")]
    public string CustomerName {
      get { return PropertyMetadata.CustomerName.GetValue(this); }
      set { PropertyMetadata.CustomerName.SetValue(this, value); }
    }
    #endregion Data Properties

    #region Navigation properties
    #endregion Navigation properties

    #region EntityProperty definitions
    public partial class PropertyMetadata {

      /// Explicit static constructor ensures static fields are initialized.
      static PropertyMetadata() {}

      /// <summary>The Id <see cref="T:IbEm.DataEntityProperty"/>. </summary>
      public static readonly IbEm.DataEntityProperty<Customer, int> Id = new IbEm.DataEntityProperty<Customer, int>("Id", false, true, IbEm.ConcurrencyStrategy.None, true, null);

      /// <summary>The CustomerName <see cref="T:IbEm.DataEntityProperty"/>. </summary>
      public static readonly IbEm.DataEntityProperty<Customer, string> CustomerName = new IbEm.DataEntityProperty<Customer, string>("CustomerName", false, false, IbEm.ConcurrencyStrategy.None, false, null);
    }
    #endregion EntityProperty definitions

    #region EntityPropertyNames
    public new partial class EntityPropertyNames : IbEm.Entity.EntityPropertyNames {
      public const String Id = "Id";
      public const String CustomerName = "CustomerName";
    }
    #endregion EntityPropertyNames
  }
  #endregion Customer class

  #region Order class

  /// <summary>The auto-generated Order class. </summary>
  [DataContract(IsReference=true)]
  [IbEm.DataSourceKeyName(@"BuyABicycleEntities")]
  [IbEm.DefaultEntitySetName(@"BuyABicycleEntities.Orders")]
  public partial class Order : IbEm.Entity {

    /// <summary>Returns the property path for the given expression. </summary>
    /// <example>
    /// Usage:
    /// <code>
    ///    var r = Employee.PathFor(e => e.Manager.City); // returns "Manager.City"
    /// </code>
    /// </example>
    public static string PathFor(System.Linq.Expressions.Expression<System.Func<Order, object>> expr) {
      return IbCore.PropertyPath.For<Order>(expr);
    }

    #region Data Properties

    /// <summary>Gets or sets the Id. </summary>
    [Key]
    [DataMember]
    [Bindable(true, BindingDirection.TwoWay)]
    [Editable(true)]
    [Display(Name="Id", AutoGenerateField=true)]
    [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Order_Id")]
    public int Id {
      get { return PropertyMetadata.Id.GetValue(this); }
      set { PropertyMetadata.Id.SetValue(this, value); }
    }

    /// <summary>Gets or sets the CustomerName. </summary>
    [DataMember]
    [Bindable(true, BindingDirection.TwoWay)]
    [Editable(true)]
    [Display(Name="CustomerName", AutoGenerateField=true)]
    [IbVal.StringLengthVerifier(MaxValue=50, IsRequired=true, ErrorMessageResourceName="Order_CustomerName")]
    public string CustomerName {
      get { return PropertyMetadata.CustomerName.GetValue(this); }
      set { PropertyMetadata.CustomerName.SetValue(this, value); }
    }

    /// <summary>Gets or sets the CustomerAddress. </summary>
    [DataMember]
    [Bindable(true, BindingDirection.TwoWay)]
    [Editable(true)]
    [Display(Name="CustomerAddress", AutoGenerateField=true)]
    [IbVal.StringLengthVerifier(MaxValue=50, IsRequired=true, ErrorMessageResourceName="Order_CustomerAddress")]
    public string CustomerAddress {
      get { return PropertyMetadata.CustomerAddress.GetValue(this); }
      set { PropertyMetadata.CustomerAddress.SetValue(this, value); }
    }

    /// <summary>Gets or sets the CustomerPhoneNumber. </summary>
    [DataMember]
    [Bindable(true, BindingDirection.TwoWay)]
    [Editable(true)]
    [Display(Name="CustomerPhoneNumber", AutoGenerateField=true)]
    [IbVal.StringLengthVerifier(MaxValue=50, IsRequired=true, ErrorMessageResourceName="Order_CustomerPhoneNumber")]
    public string CustomerPhoneNumber {
      get { return PropertyMetadata.CustomerPhoneNumber.GetValue(this); }
      set { PropertyMetadata.CustomerPhoneNumber.SetValue(this, value); }
    }

    /// <summary>Gets or sets the CustomerEmail. </summary>
    [DataMember]
    [Bindable(true, BindingDirection.TwoWay)]
    [Editable(true)]
    [Display(Name="CustomerEmail", AutoGenerateField=true)]
    [IbVal.StringLengthVerifier(MaxValue=50, IsRequired=true, ErrorMessageResourceName="Order_CustomerEmail")]
    public string CustomerEmail {
      get { return PropertyMetadata.CustomerEmail.GetValue(this); }
      set { PropertyMetadata.CustomerEmail.SetValue(this, value); }
    }

    /// <summary>Gets or sets the BicycleModel. </summary>
    [DataMember]
    [Bindable(true, BindingDirection.TwoWay)]
    [Editable(true)]
    [Display(Name="BicycleModel", AutoGenerateField=true)]
    [IbVal.StringLengthVerifier(MaxValue=50, IsRequired=true, ErrorMessageResourceName="Order_BicycleModel")]
    public string BicycleModel {
      get { return PropertyMetadata.BicycleModel.GetValue(this); }
      set { PropertyMetadata.BicycleModel.SetValue(this, value); }
    }

    /// <summary>Gets or sets the BicycleSize. </summary>
    [DataMember]
    [Bindable(true, BindingDirection.TwoWay)]
    [Editable(true)]
    [Display(Name="BicycleSize", AutoGenerateField=true)]
    [IbVal.StringLengthVerifier(MaxValue=50, IsRequired=true, ErrorMessageResourceName="Order_BicycleSize")]
    public string BicycleSize {
      get { return PropertyMetadata.BicycleSize.GetValue(this); }
      set { PropertyMetadata.BicycleSize.SetValue(this, value); }
    }

    /// <summary>Gets or sets the BicycleColour. </summary>
    [DataMember]
    [Bindable(true, BindingDirection.TwoWay)]
    [Editable(true)]
    [Display(Name="BicycleColour", AutoGenerateField=true)]
    [IbVal.StringLengthVerifier(MaxValue=50, IsRequired=true, ErrorMessageResourceName="Order_BicycleColour")]
    public string BicycleColour {
      get { return PropertyMetadata.BicycleColour.GetValue(this); }
      set { PropertyMetadata.BicycleColour.SetValue(this, value); }
    }
    #endregion Data Properties

    #region Navigation properties
    #endregion Navigation properties

    #region EntityProperty definitions
    public partial class PropertyMetadata {

      /// Explicit static constructor ensures static fields are initialized.
      static PropertyMetadata() {}

      /// <summary>The Id <see cref="T:IbEm.DataEntityProperty"/>. </summary>
      public static readonly IbEm.DataEntityProperty<Order, int> Id = new IbEm.DataEntityProperty<Order, int>("Id", false, true, IbEm.ConcurrencyStrategy.None, true, null);

      /// <summary>The CustomerName <see cref="T:IbEm.DataEntityProperty"/>. </summary>
      public static readonly IbEm.DataEntityProperty<Order, string> CustomerName = new IbEm.DataEntityProperty<Order, string>("CustomerName", false, false, IbEm.ConcurrencyStrategy.None, false, null);

      /// <summary>The CustomerAddress <see cref="T:IbEm.DataEntityProperty"/>. </summary>
      public static readonly IbEm.DataEntityProperty<Order, string> CustomerAddress = new IbEm.DataEntityProperty<Order, string>("CustomerAddress", false, false, IbEm.ConcurrencyStrategy.None, false, null);

      /// <summary>The CustomerPhoneNumber <see cref="T:IbEm.DataEntityProperty"/>. </summary>
      public static readonly IbEm.DataEntityProperty<Order, string> CustomerPhoneNumber = new IbEm.DataEntityProperty<Order, string>("CustomerPhoneNumber", false, false, IbEm.ConcurrencyStrategy.None, false, null);

      /// <summary>The CustomerEmail <see cref="T:IbEm.DataEntityProperty"/>. </summary>
      public static readonly IbEm.DataEntityProperty<Order, string> CustomerEmail = new IbEm.DataEntityProperty<Order, string>("CustomerEmail", false, false, IbEm.ConcurrencyStrategy.None, false, null);

      /// <summary>The BicycleModel <see cref="T:IbEm.DataEntityProperty"/>. </summary>
      public static readonly IbEm.DataEntityProperty<Order, string> BicycleModel = new IbEm.DataEntityProperty<Order, string>("BicycleModel", false, false, IbEm.ConcurrencyStrategy.None, false, null);

      /// <summary>The BicycleSize <see cref="T:IbEm.DataEntityProperty"/>. </summary>
      public static readonly IbEm.DataEntityProperty<Order, string> BicycleSize = new IbEm.DataEntityProperty<Order, string>("BicycleSize", false, false, IbEm.ConcurrencyStrategy.None, false, null);

      /// <summary>The BicycleColour <see cref="T:IbEm.DataEntityProperty"/>. </summary>
      public static readonly IbEm.DataEntityProperty<Order, string> BicycleColour = new IbEm.DataEntityProperty<Order, string>("BicycleColour", false, false, IbEm.ConcurrencyStrategy.None, false, null);
    }
    #endregion EntityProperty definitions

    #region EntityPropertyNames
    public new partial class EntityPropertyNames : IbEm.Entity.EntityPropertyNames {
      public const String Id = "Id";
      public const String CustomerName = "CustomerName";
      public const String CustomerAddress = "CustomerAddress";
      public const String CustomerPhoneNumber = "CustomerPhoneNumber";
      public const String CustomerEmail = "CustomerEmail";
      public const String BicycleModel = "BicycleModel";
      public const String BicycleSize = "BicycleSize";
      public const String BicycleColour = "BicycleColour";
    }
    #endregion EntityPropertyNames
  }
  #endregion Order class

  #region EntityRelations

  /// <summary>
  /// A generated class that returns the relations between entities in this model.
  /// </summary>
  [IbCore.IdeaBladeGuid("ada4f853-5b03-423a-a51f-0da38018c087", "2.1.4")]
  public partial class EntityRelations : IbEm.IEntityRelations {

    /// Explicit static constructor ensures static fields are initialized.
    static EntityRelations() {}
  }
  #endregion EntityRelations
}

【问题讨论】:

  • BuyABicycleEntities 的类型是 DbContext 吗?
  • 如果你想使用using 语句,是的,你需要为BuyABicycleEntities 实现IDisposable。 (请记住,您本身不必这样做,但这是个好主意)
  • 不是 100% 我是从添加实体数据模型向导的模板中添加的。我该如何检查?
  • @TimothyGroote 如果在Dispose() 期间有适当的事情要做,这只是一个好主意。如果它还没有实现,我猜:它可能不需要
  • 你能发布BuyABicycleEntities继承/实现的基类/接口吗?

标签: c# asp.net asp.net-mvc-4 idisposable devforce


【解决方案1】:

错误说 BuyABicycleEntities 应该从 IDisposable 接口继承。看起来你正在使用实体框架,所以数据库上下文应该已经继承了它,所以请检查你是否正确使用了实体框架。

详情请看这里-Working with DbContext

更新:

如果您使用 IdeaBlade EntityManager,则无需将代码包装在使用中

【讨论】:

  • 是的,我使用模板添加实体数据模型向导。但我没有提到 dbContext
  • 能否请您更新您的问题并显示您的 BuyABicycleEntities 课程?
  • 只是不要使用“使用”——它不需要。 drc.ideablade.com/xwiki/bin/view/Documentation/…
【解决方案2】:
  • 通过添加此方法使您的上下文类 IDisposable BuyABicycleEntities : IDisposable
  • 现在在 BuyABicycleEntities 类上添加一个实现 IDisposable 的方法

    void IDisposable.Dispose(){ 
    
    }
    
  • 现在确保您正在使用创建操作方法的项目中安装了实体框架。如果没有,请从 Nuget 安装 Entity Framework。

【讨论】:

  • 上面的答案中是否说过如果您使用实体框架和IdeaBlade EntityManager,则不需要实现IDisposable方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多