开发者

Is it possible to relate two entities without retrieving them from database in Entity Framework 4.1?

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 { 开发者_StackOverflow中文版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!


Attach is made for such a scenario:

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.Entity2List.Attach(entity1.ReferenceToEntity2); // must be BEFORE Add
    db.Entity1List.Add(entity1);
    db.SaveChanges();
}

It tells EF that Entity2 with ID = 1 already exists in the database. The entity is in Unchanged state after Attach and EF won't send any UPDATE or INSERT statement to the database for this entity. Just the foreign key in entity1 is updated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜