在我的Index View页面中,我希望以表格形式显示所有实体(显示标题、描述等),用户名称、地区名称和类别名称也要一并展示。
以下是我在控制器中的操作:
public ActionResult Index()
{
var model = this.UnitOfWork.EntityRepository.Get();
return View(model);
}
在我的代码仓库中,我做了这个操作:
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = _dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
我经常在最后一个规则(
return query.ToList()
)中遇到错误信息Input string was not in a correct format
。但是,当我检查了规则
IQueryable<TEntity> query = _dbSet;
后,它已经出现了错误:There is already an open DataReader associated with this Connection which must be closed first.
。这可能是因为我想从多个表中选择。 但是我该如何解决呢? 我尝试将
MultipleActiveResultSets=True"
添加到我的ConnectionString中,就像这样:<connectionStrings>
<add name="reuzzeCS" connectionString="server=localhost;uid=root;pwd=*****;Persist Security Info=True;database=reuzze;MultipleActiveResultSets=True"" providerName="MySql.Data.MySqlClient" />
但是这给了我一个错误,说关键词不存在,因为我使用的是 MySql.Data.MySqlClient ..
执行的查询是:
{SELECT
Extent1
.entity_id
,Extent1
.entity_title
,Extent1
.entity_description
,Extent1
.entity_starttime
,Extent1
.entity_endtime
,Extent1
.entity_instantsellingprice
,Extent1
.entity_shippingprice
,Extent1
.entity_condition
,Extent1
.entity_views
,Extent1
.entity_created
,Extent1
.entity_modified
,Extent1
.entity_deleted
,Extent1
.user_id
,Extent1
.region_id
,Extent1
.category_id
FROMentities
ASExtent1
}
但是当他想要执行查询并且我想要扩展结果时,我得到了错误 已经有一个与此连接关联的打开的 DataReader,必须先关闭
编辑:
我的完整存储库:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace App.Data.orm.repositories
{
// REPO FROM TEACHER
public class GDMRepository<TEntity> where TEntity : class
{
internal GDMContext _context;
internal DbSet<TEntity> _dbSet;
public GDMRepository(GDMContext context)
{
this._context = context;
this._dbSet = _context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = _dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return _dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
_dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = _dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entity)
{
if (_context.Entry(entity).State == EntityState.Detached)
{
_dbSet.Attach(entity);
}
_dbSet.Remove(entity);
}
public virtual void Update(TEntity entity)
{
_dbSet.Attach(entity);
_context.Entry(entity).State = EntityState.Modified;
}
}
}
GDMContext class:
using App.Data.orm.mappings;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace App.Data.orm
{
public class GDMContext:DbContext
{
public GDMContext() : base("reuzzeCS") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//REMOVE STANDARD MAPPING IN ENTITY FRAMEWORK
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//REGISTER MAPPERS
modelBuilder.Configurations.Add(new UserMapping());
modelBuilder.Configurations.Add(new PersonMapping());
modelBuilder.Configurations.Add(new RoleMapping());
modelBuilder.Configurations.Add(new EntityMapping());
modelBuilder.Configurations.Add(new MediaMapping());
modelBuilder.Configurations.Add(new BidMapping());
modelBuilder.Configurations.Add(new CategoryMapping());
modelBuilder.Configurations.Add(new AddressMapping());
modelBuilder.Configurations.Add(new RegionMapping());
modelBuilder.Configurations.Add(new MessageMapping());
}
}
}
我的实体模型:
public class Entity
{
public Int64 Id { get; set; }
[Required(ErrorMessage = "Title is required")]
[StringLength(255)]
[DisplayName("Title")]
public string Title { get; set; }
[Required(ErrorMessage = "Description is required")]
[DisplayName("Description")]
public string Description { get; set; }
[Required]
public DateTime StartTime { get; set; }
[Required]
public DateTime EndTime { get; set; }
/*[Required(ErrorMessage = "Type is required")]
[StringLength(16)]
[DisplayName("Type")]
public string Type { get; set; }*/
[Required]
public decimal InstantSellingPrice { get; set; }
public Nullable<decimal> ShippingPrice { get; set; }
public Condition? Condition { get; set; }
public Nullable<Int64> Views { get; set; }
[Required]
public DateTime CreateDate { get; set; }
public Nullable<DateTime> ModifiedDate { get; set; }
public Nullable<DateTime> DeletedDate { get; set; }
public Int32 UserId { get; set; }
public Int32 RegionId { get; set; }
public Int16 CategoryId { get; set; }
public virtual User User { get; set; }
public virtual Region Region { get; set; }
public virtual Category Category { get; set; }
//public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<User> Favorites { get; set; }
public virtual ICollection<Bid> Bids { get; set; }
public virtual ICollection<Media> Media { get; set; }
}
public enum Condition
{
New = 1,
Used = 2
}
我的实体映射:
internal class EntityMapping : EntityTypeConfiguration<Entity>
{
public EntityMapping()
: base()
{
this.ToTable("entities", "reuzze");
this.HasKey(t => t.Id);
this.Property(t => t.Id).HasColumnName("entity_id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(t => t.Title).HasColumnName("entity_title").IsRequired().HasMaxLength(255);
this.Property(t => t.Description).HasColumnName("entity_description").IsRequired();
this.Property(t => t.StartTime).HasColumnName("entity_starttime").IsRequired();
this.Property(t => t.EndTime).HasColumnName("entity_endtime").IsRequired();
//this.Property(t => t.Type).HasColumnName("entity_type").IsRequired();
this.Property(t => t.InstantSellingPrice).HasColumnName("entity_instantsellingprice").IsRequired();
this.Property(t => t.ShippingPrice).HasColumnName("entity_shippingprice").IsOptional();
this.Property(t => t.Condition).HasColumnName("entity_condition").IsRequired();
this.Property(t => t.Views).HasColumnName("entity_views").IsOptional();
this.Property(t => t.CreateDate).HasColumnName("entity_created").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
this.Property(t => t.ModifiedDate).HasColumnName("entity_modified").IsOptional();
this.Property(t => t.DeletedDate).HasColumnName("entity_deleted").IsOptional();
this.Property(t => t.UserId).HasColumnName("user_id").IsRequired();
this.Property(t => t.RegionId).HasColumnName("region_id").IsRequired();
this.Property(t => t.CategoryId).HasColumnName("category_id").IsRequired();
//FOREIGN KEY MAPPINGS
this.HasRequired(t => t.User).WithMany(p => p.Entities).HasForeignKey(f => f.UserId).WillCascadeOnDelete(false);
this.HasRequired(t => t.Region).WithMany(p => p.Entities).HasForeignKey(f => f.RegionId);
this.HasRequired(t => t.Category).WithMany(p => p.Entities).HasForeignKey(f => f.CategoryId);
//MANY_TO_MANY MAPPINGS
this.HasMany(t => t.Favorites)
.WithMany(t => t.Favorites)
.Map(mc =>
{
mc.ToTable("favorites");
mc.MapLeftKey("entity_id");
mc.MapRightKey("user_id");
});
}
}
更新:
- 基础 {选择
Extent1
.entity_id
,Extent1
.entity_title
,Extent1
.entity_description
,Extent1
.entity_starttime
,Extent1
.entity_endtime
,Extent1
.entity_instantsellingprice
,Extent1
.entity_shippingprice
,Extent1
.entity_condition
,Extent1
.entity_views
,Extent1
.entity_created
,Extent1
.entity_modified
,Extent1
.entity_deleted
,Extent1
.user_id
,Extent1
.region_id
,Extent1
.category_id
从entities
中选取 ASExtent1
} System.Data.Entity.Internal.Linq.InternalQuery {System.Data.Entity.Internal.Linq.InternalSet}
ToList()
,以便查询执行。(即:您不能使用MySQL一次执行多个查询)。 - Kenneth