良い一日!EF 5 Beta 2 CodeFirst を使用しています。私のエンティティでは、最初に ConsoleApplication と Repository を作成しましたが、dll を作成してこのリポジトリを使用すると、リポジトリを使用しようとすると 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);
}
}
助けてくれてありがとう。