再会!我使用 EF 5 Beta 2 CodeFirst。对于我的实体,我首先创建了运行良好的 ConsoleApplication 和 Repository,但是当我创建 dll 并使用此 Repository 时,我在尝试使用 Repository 时遇到了 ObjectDisposedException。
样品(中var user = (new Repository().GetElementById<ReposirotyEF.User>(resultTesting.Users.Id) as ReposirotyEF.User);
):
public static ResultModel PopulateResultModel(ResultTesting resultTesting)
{
string name = string.Empty;
var user = (new Repository().GetElementById<ReposirotyEF.User>(resultTesting.Users.Id) as ReposirotyEF.User);
name = user.Name;
return new ResultModel()
{
Id = resultTesting.Id,
Name = name,
Result = resultTesting.Result,
Answers = resultTesting.Answers,
Data = resultTesting.TimeEnd,
RightAnswers = resultTesting.RightAnswers,
Time = resultTesting.Time
};
}
或者:
public void SaveOrUpdate<T>(T obj)
{
using (var context = new ContextTest1())
{
switch (typeof(T).Name)
{
case "User":
User user = context.Users.ToList().Find(u => u.Id == (obj as User).Id);
User newUser = obj as User;
if (user != null)
{
user = newUser;
}
else
{
context.Users.Add(newUser);
}
break;
case "ResultTesting":
var resultTesting = context.ResultTestings.ToList().Find(u => u.Id == (obj as ResultTesting).Id);
var newRes = obj as ResultTesting;
if (resultTesting != null)
{
resultTesting = newRes;
}
else
{
context.ResultTestings.Add(newRes);
}
break;
case "Question":
var question = context.Questions.ToList().Find(u => u.Id == (obj as Question).Id);
var newQue = obj as Question;
if (question != null)
{
question = newQue;
}
else
{
context.Questions.Add(newQue);
}
break;
default:
//context.CurrentTestings.ToList().Remove(obj as CurrentTesting);
var currentTesting = context.CurrentTestings.ToList().Find(u => u.Id == (obj as CurrentTesting).Id);
var newCur = obj as CurrentTesting;
if (currentTesting != null)
{
currentTesting = newCur;
}
else
{
context.CurrentTestings.Add(newCur);
}
break;
}
context.SaveChanges();
}
}
在context.CurrentTestings.Add(newCur);
和我的GetElementById
(不好):
public IId GetElementById<T>(int id)
where T : IId
{
using (var context = new ContextTest1())
{
switch (typeof(T).Name)
{
case "User":
return context.Users.ToList().Find(u => u.Id == id);
case "ResultTesting":
return context.ResultTestings.ToList().Find(u => u.Id == id);
case "Question":
return context.Questions.ToList().Find(u => u.Id == id);
}
return context.CurrentTestings.ToList().Find(u => u.Id == id);
}
}
谢谢你的帮助。