Hry*_*rii 2 sql entity-framework views asp.net-mvc-3
我使用Entity Framework 4.3.1.0
SQL Server 2008 Express
我有意见
SELECT dbo.Dealers.Name AS DealerName,
dbo.Dealers.LogoImage,
dbo.DealersProducts.Price,
dbo.DealersProducts.StatusType,
dbo.Products.Description,
dbo.Products.Name,
dbo.DealersProducts.DealerId,
dbo.Products.Id
FROM dbo.Dealers
INNER JOIN
dbo.DealersProducts
ON dbo.Dealers.Id = dbo.DealersProducts.DealerId
INNER JOIN
dbo.Products
ON dbo.DealersProducts.ProductId = dbo.Products.Id
Run Code Online (Sandbox Code Playgroud)
我有实体
public class DealerViews : BasePersistentEntity
{
public int DealerId { get; set; }
public string DealerName { get; set; }
public string LogoImage { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public int StatusType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这个我用于退货经销商的View有请求产品.当我在SQL Manager中请求SQL查询时,我获得了正确的结果但在实体框架中我得到了奇怪的结果.例子
SQL结果
经销商1
经销商2
实体框架结果
经销商1
经销商1
控制器代码
public ActionResult ShowProductDealers(int id)
{
var dealer = this.dealerService.GetDealerByProductId(id);
return this.PartialView("ShowProductDealers", dealer);
}
Run Code Online (Sandbox Code Playgroud)
服务代码
public IEnumerable<DealerViews> GetDealerByProductId(int id)
{
return this.repositoryViews.All.Where(item => item.Id == id);
}
Run Code Online (Sandbox Code Playgroud)
存储库中的代码
public class SGNRepository<T> where T : BasePersistentEntity
{
public readonly SGNContext<T> Context = new SGNContext<T>();
public IQueryable<T> All
{
get { return this.Context.Table; }
}
public IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = this.Context.Table;
return includeProperties.Aggregate(query, (current, includeProperty) => current.Include(includeProperty));
}
public T Find(int id)
{
return this.Context.Table.Find(id);
}
public void InsertOrUpdate(T item)
{
if (item.Id == default(int))
{
// New entity
this.Context.Table.Add(item);
}
else
{
// Existing entity
this.Context.Entry(item).State = EntityState.Modified;
}
this.Save();
}
public void Delete(int id)
{
var item = this.Context.Table.Find(id);
this.Context.Table.Remove(item);
this.Save();
}
private void Save()
{
this.Context.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
这是您的映射问题.您选择哪个列作为实体的主键?我希望在这种情况下你有Product.Id主键,这个产品有很多经销商.
EF使用主键作为唯一标识.必须唯一标识每条记录.如果EF加载记录并且在其内部标识映射中没有其唯一标识,则它从该记录创建和实体实例并将其放入标识映射.下次获取具有相同唯一标识的记录时,它不会创建新的实体实例,而是使用存储在标识映射中的实例.这就是你得到相同结果的原因.
顺便说一句.您的存储库是错误的,因为您无法插入,删除或更新从视图创建的实体(除非您为所有这些操作映射存储过程或自定义SQL命令),因此它不应公开此类方法.
另一点是为什么当它包装单个call =没有附加值时没有存储库和服务,并且没有理由这样做,特别是当您的存储库仅支持对一个实体类型的简单CRUD操作时.
| 归档时间: |
|
| 查看次数: |
1016 次 |
| 最近记录: |