我正在使用EF5。我已經使用代碼第一種方法。我在使用存儲過程時遇到錯誤。錯誤是EF:實體類型不是使用存儲過程的當前上下文的模型的一部分
"The entity type CustomProduct is not part of the model for the current context."
在Db中有3個表。
產品
- 產品編號
- 產品名稱
- ProductDesription
ProuctVaraint
- ProductVaraintId
- 產品編號
- ProductVaraintName
- 股票
- 尺寸
ProductPrice
- ProductPriceId
- ProudctId
- 價格
和每個實體都有單獨的類與具有的所有屬性。
- Product.cs
- ProductVaraint.cs
- ProductPrice.cs
這裏是所有類
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
}
public class ProductVaraint
{
public int ProductVaraintId { get; set; }
public int ProductId { get; set; }
public string ProdcutVaraintName { get; set; }
public int Stock { get; set; }
public int Size { get; set; }
}
public class ProductPrice
{
public int ProductPriceId { get; set; }
public int ProductId { get; set; }
public decimal Price { get; set; }
}
public class CustomProduct
{
public int ProudctId { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public int Stock { get; set; }
public int Size { get; set; }
public decimal Price { get; set; }
}
在這裏被存儲的過程
public IList<CustomProduct> ExecuteSP()
{
var context = ((IObjectContextAdapter)(this)).ObjectContext;
var connection = this.Database.Connection;
//open the connection
if (connection.State == ConnectionState.Closed)
connection.Open();
//create a command object
using (var cmd = connection.CreateCommand())
{
//command to execute
cmd.CommandText = "GetProducts";
cmd.CommandType = CommandType.StoredProcedure;
var reader = cmd.ExecuteReader();
var result = context.Translate<CustomProduct>(reader).ToList();
for (int i = 0; i < result.Count; i++)
result[i] = AttachEntityToContext(result[i]);
reader.Close();
return result;
}
}
}
public TEntity AttachEntityToContext<TEntity>(TEntity entity) where TEntity : BaseEntity, new()
{
var alreadyAttached = Set<TEntity>().Local.Where(x => x.Id == entity.Id).FirstOrDefault();
if (alreadyAttached == null)
{
Set<TEntity>().Attach(entity);
return entity;
}
else
{
return alreadyAttached;
}
}
我映射Product.cs,ProductVaraint.cs並用的DbContext ProductPrice.cs但不映射CustomProduct.cs
現在,我做了一個存儲過程,從產品退回產品名稱(從產品),產品描述( ),Stock(來自ProductVaraint),Size(來自ProductVaraint)和Price(來自ProductPrice)。
要映射這個屬性,我有一個名爲CustomProudct.cs的單獨的類,它包含存儲過程返回的所有這些屬性,並將這個類映射到存儲過程。
CustomProduct沒有單獨的表格,我不需要爲映射sp結果創建額外的表格。
我知道沒有單獨的CustomProduct表的原因,並且EF正試圖在Db中搜索此表,並且它沒有找到任何表,這就是它拋出異常的原因。
請有人建議我如何做到這一點。有沒有其他辦法來處理這種情況?
代碼將有助於理解這一點,並建議出路 – tariq