I am facing a problem getting Entity Framework to save results from yield return properly. To illustrate the problem I created 2 sets of methods, one returns an entity and the other returns an IEnumerable using yield return. Journal references UserProfile.
Set 1:
public static UserProfile CreateUser()
{
return new UserProfile() {
UserId = Guid.Parse("60a3987c-0aa6-4a93- a5d2-68c51122858b"),
UserName = "jason"
};
}
public static Journal CreateJournal(UserProfile userProfile)
{
return new Journal() { UserProfile = userProfile };
}
Set 2:
public static IEnumerable<UserProfile> CreateUsers()
{
yield return new UserProfile() {
UserId =
Guid.Parse("02cd1e9f-5947-4b08-9616-5b4f4033d074"),
UserName = "john"
};
}
public static IEnumerable<Journal> CreateJournals(UserProfile userProfile)
{
yield return new Journal() { UserProfile = userProfile };
}
TestSet1 and TestSet2 save the results from Set1 and Set2 respectively. TestSet1 works but TestSet2 throws an exception of Violation of PRIMARY KEY constraint 'PK_dbo.UserProfiles'. Another observation - if I initialize a List and return it instead of yield return then it works.
public static void TestSet1()
{
var u = CreateUser();
var j = CreateJournal(u);
_db.UserProfiles.Add(u);
_db.Journals.Add(j);
_db.Commit();
}
public static void TestSet2()
{
var uList = CreateUsers();
var jList = CreateJournals(uList.ElementAt(0));
_db.UserProfiles.Add(uList.ElementAt(0));
_db.Journals.Add(jList.ElementAt(0));
_db.Commit();
}
What is your view on why yield return in Set2 doesn't work? Thanks