Reputation: 4784
I'm new to entity frame work code first. I have simple class called Cat and a list of cats, when i'm doing the following :
mAllAnimals.Add(new Cat() { Father = null , Name = "Father Kitten", NickName = "Shmil" });
mAllAnimals.Add(new Cat() { Father = mAllAnimals.First(a => a.Name == "Father Kitten") , Name = "Son Kitten" , NickName = "son" });
i get an exception,because he couldn't find "Father kitten", but when i put between the to statements "SaveChanges()" it works perfectly.
This is very strange for me, do i actually need to save every step of the way ? can't he search on the local copy and on the db, i thought that part of the fun in entity framework is that i can work "normally" with my class and doesn't have to save my changes every step of the way. Can i make him "auto save" every step i do, so i won't have to write all the time "SaveChanges"
One more question, i worked previously with NHibrnate and all the mapping where made using simple XML files. i don't see any files here, were is the mapping ? can i change it ?
Thanks in advance
Upvotes: 1
Views: 179
Reputation: 6050
On the lack of an .edmx, see:
http://blogs.msdn.com/b/adonet/archive/2011/03/07/when-is-code-first-not-code-first.aspx
Code First does not use an .edmx file, and it is also called Code Only for that reason. You do the mapping using attributes or fluent API. See the first two posts in the 12-part series on the Entity Framework blog:
Upvotes: 3
Reputation: 160892
This should work:
Cat father = new Cat() { Father = null , Name = "Father Kitten", NickName = "Shmil" };
Cat son = new Cat() { Father = father , Name = "Son Kitten" , NickName = "son" };
mAllAnimals.Add(father);
mAllAnimals.Add(son);
context.SaveChanges();
The reason your version doesn't work is that you are looking for the father
entity in the database - but you will only add it to the DB when you call SaveChanges()
As for the mapping - your project should have an .edmx
file - double clicking that will bring up a designer which also allows you to modify the mapping.
Upvotes: 3