這使我瘋了。我試圖做一個「簡單」的記錄插入,我只能讓它工作,如果我將上下文存儲在變量中或創建本地上下文。我試圖將上下文和模型對象綁在一起,但目前爲止還沒有運氣。MVC簡單插入不更新數據庫
public class TransactionDataAccessLayer
{
public cartableContext transactionContext
{
get
{
return new cartableContext();
}
}
}
class TransactionBusinessLayer
{
Cardata newCar = new Cardata();
public void addCar(Cardata cd)
{
try
{
//this works. Storing the context in ctc2 seems to make it work???
TransactionDataAccessLayer tdal = new TransactionDataAccessLayer();
cartableContext ctc2 = tdal.transactionContext;
ctc2.cardata.Add(cd);
ctc2.SaveChanges();
//this does not work
tdal.transactionContext.cardata.Add(cd);
tdal.transactionContext.Entry(cd).State = EntityState.Modified;
tdal.transactionContext.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
}
}
}
如何將這項工作如果返回每次訪問'transactionContext'財產時新環境?所有這些行爲都應該發生在同一個環境中,這就是爲什麼其他方法有效。在MVC中,通常每個請求都有一個上下文。 – 2014-10-02 10:42:13