How to Call StoreProcedure : http://www.tudou.com/programs/view/0WtDy50Hbzs/target=_blank
If it not work ,see: http://stackoverflow.com/questions/3825412/entity-framework-4-function-import-not-working
public partial class CarSystemEntities : DbContext
{......
public virtual int AddNewCompany(string name, string address)
{
var nameParameter = name != null ?
new ObjectParameter("Name", name) :
new ObjectParameter("Name", typeof(string));
var addressParameter = address != null ?
new ObjectParameter("Address", address) :
new ObjectParameter("Address", typeof(string));
//Auto generated code ,
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("AddNewCompany", nameParameter, addressParameter);
}
}
Include:
现在项目有这样一个功能,就是先将数据查询出来,然后将查询出来的数据导成excel。系统采用的是entityframework框架,数据访问层用的是linq,
于是我这样写查询的底层方法:
var res = from b in dataContext.B
where ((string.IsNullOrEmpty(txtname) || b.Name.ToUpper().Contains(txtname.ToUpper())) 再加上一些其他的查询条件,很快写完了,自我感觉很不错,于是测试一下,但是在测试的过程中发现有一个问题,查询的时候没有错,但是填充excel时出现这样一个错:“The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.”(查询和填充excel都是同一个数据源,都是调的一个底层方法)。很多人可能会感到奇怪了,同样是一个底层方法,为什么查询不出错,填充excel的时候不出错呢?这时include就起作用的了.我们知道inlcude的作用是“返回其关联实体”,但是很多时候却不知道返回来的关联实体有什么用,关联实体又是什么。前面已经说了,数据访问层用linq实现,那么回到系统架构的DomainEntities 模型中, 查看查询表的结构,可以找到相应的实体。这时加上关联的实体
var res= from b in dataContext.B.include("BA").include("BC").include("BA.D")
where ((string.IsNullOrEmpty(txtname) || b.Name.ToUpper().Contains(txtname.ToUpper()))再加上一个其他的查询条件,这是在测试一下,发现程序运行正常。
其中“BA”和“BC”是b的关联实体,可以在DomainEntities找到,但是include("BA.D")呢,这是通过B的关联实体BA去访问D表,然后再执行填充excel。
Join :
using (var edm = new NorthwindEntities()) {
var query = from d in edm.Order_Details
join order in edm.Orders
on d.OrderID equals order.OrderID
select new
{
OrderId = order.OrderID,
ProductId = d.ProductID,
UnitPrice = d.UnitPrice
};
通用方法 Update 各种类型 Entity:
///
/// Update the Entity, the Logic is get orignal Entity Key, then update the object, So update the Primary key is forbidden.
///
///
/// the object need to be update.
///
/// default is TypeName of entity, so skip this if entity same with entitySet
protected void Update
where T : Entity.EntityBase
{
if (entityToUpdate == null) return;
if (string.IsNullOrEmpty(entitySetName))
{
entitySetName = entityToUpdate.GetType().Name;
}
var result = Utility.Execute(db =>
{
var oc = ((IObjectContextAdapter)db).ObjectContext;
var key = oc.CreateEntityKey(entitySetName, entityToUpdate);
oc.GetObjectByKey(key);
oc.ApplyCurrentValues(entitySetName, entityToUpdate);
});
if (entityUpdated != null)
{
entityUpdated(this, null);
}
if (LogMessage != null)
{
LogMessage(entitySetName + " Updated Successful");
}
}