开发者

EF 4 POCO: Saving a new entity with multiple related entities

Let's say I have the following POCO entities:

public class CellPhone {
    public Manufacturer PhoneManufacturer;
    public ICollection<Color> PhoneColor { get; set; }        
    public string Version { get; set; }
}

public class Manufacturer {
    public int ID { get; set;}
    public string Name { get; set; }
}

public class Color {
    public int ID { get; set;}
    public string Name { get; set; }

}

I have an ObjectSet for each of those entities in my ObjectContext class.

When creating a new CellPhone instance I usually 开发者_Python百科have the IDs of both Manufacturer and Color, so in order to add a reference from my new CellPhone instance to the correct Manufacturer and Color entities, I need to first retrieve them using the same context (query their ObjectSet for the ID), set the relevant navigation properties of the CellPhone instance, and then save the new CellPhone instance (add it to the ObjectSet and SaveChanges()).

In case I have more than 2 related entities to a class like CellPhone this process becomes not efficient.

Is there a way to do it more efficiently? i.e. without querying the DB for each related entity?

Thank you for helping.

Jane


you can keep the foreign key properties with your model class. Then you don't need to use Find by Id .

public class CellPhone {
     public Manufacturer PhoneManufacturer;
     public int PhoneManufacturerId { get; set; }//foreignkey
    public ICollection<Color> PhoneColor { get; set; }        
    public string Version { get; set; }
}

now you can do like this,

 CellPhone cellpHone=new CellPhone {PhoneManufacturerId =2,Version= ""};
   context.Attach(cellpHone);
   context.SaveChanges();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜