Note that there are some explanatory texts on larger screens.

plurals
  1. POEF Code First, create new object in collection with a proxy
    primarykey
    data
    text
    <p>How can I create+persist+have-a-proxy-to a new instance of a code-first poco using only navigation property collections? In the bellow code, I show how you might want to do this, if using member functions to create POCOs that then create POCOs. You don't have a DbContext, but if you create an object and persist it using DbSet.Add, the returned object isn't a proxy, so you can't in turn use its DbSet.Add to add a different sub-object.</p> <p>In this code, if you call MailingList.AddIncomingMessage("my message"), you get an exception at the "OOPS" comment, because the created msg isn't a proxy and thus its Message.doodads property is null.</p> <pre><code>class Doodad { public int ID { get; set; } public string doodad { get; set; }; } class Message { public int ID { get; set; } public virtual MailingList mailingList { get; set; } public virtual ICollection&lt;Doodad&gt; doodads { get; set; } public string text { get; set; } public void GetDoodadCreateIfNeeded(string doodad) { try { // won't be found since we just created this Message return this.doodads.First(d =&gt; d.doodad == doodad); } catch (Exception e) { Doodad newDoodad = new Doodad() { doodad=doodad }; // OOPS! this.doodads == null, because its not a proxy object this.doodads.Add(newDoodad); return newDoodad; } } } class MailingList { public int ID { get; set; } public virtual ICollection&lt;Message&gt; messages { get; set; } public void AddIncomingMessage(string message) { var msg = new Message() { text=message }; // we have no Context, because we're in a POCO's member function this.messages.Add(msg); var doodad = msg.GetDoodadCreateIfNeeded("bongo drums"); } } </code></pre> <p>EDIT: sorry guys, I forgot to put the property accessors and ID in for this simplified case, but I am using them in the actual code.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload