Consider the following scenario:
public class Entity1
{
virtual public Int32 ID { get; set; }
[Required]
virtual public String Name { get; set; }
[Required]
virtual public Entity2 ReferenceToEntity2 { get; set; }
}
public class Entity2
{
virtual public Int32 ID { get; set; }
[Required]
virtual public String Name { get; set; }
virtual public IList<Entity1> ListOfEntity1 { get; set; }
}
[TestClass]
public class EntityFrameworkTests
{
[TestMethod]
public void Should_save_entity_with_reference_to_entity_with_required_fields()
{
using (var db = new MyContext())
{
var entity1 = new Entity1
{
Name = "My name",
ReferenceToEntity2 = new Entity2 { ID = 1 } // reference (Entity2 with ID=1) already exists in the database
};
db.Entity1List.Add(entity1);
db.SaveChanges(); // exception here
}
}
[TestMethod]
[ExpectedException(typeof(DbEntityValidationException))]
public void Should_not_save_empty_entity2_name()
{
using (var db = new MyContext())
{
var entity2 = new Entity2 { Name = "" };
db.Entity2List.Add(entity2);
db.SaveChanges();
}
}
}
The first test is not passing. A DbEntityValidationException is raised, referring to the Name property of Entity2 when trying to save Entity1 instance.
I know that I could load entity2 instance by ID and associate it using entity1.ReferenceToEntity2 = db.Entity2List.Find(entity2Id), for example. But I actually have a entity with lots of references, and I don’t want to go to database 10 times only to associate a foreign key!
Is it possible to insert a new entity1 instance into the database relating to an existing entity2 record without having to go to database to retrieve entity2?
Thanks in advance!
Attachis made for such a scenario:It tells EF that
Entity2withID= 1 already exists in the database. The entity is inUnchangedstate afterAttachand EF won’t send any UPDATE or INSERT statement to the database for this entity. Just the foreign key inentity1is updated.