开发者

CTP5 POCO Code-Only, how to add master-detail records to DB

I am trying EF CTP5 POCO, and converting from EF4 EntityModel to POCO Code Only Approach.

internal class InvoiceContext : DbContext
{
    public DbSet<Invoice> Invoices {get; set;}
    public DbSet<InvoiceLine> InvoiceLines {get; set;}
}

public class Invoice
{
    public Guid InvoiceId { get; set; }
    public virtual ICollection<InvoiceLine> Lines { get; set; }
}

public class InvoiceLine
{
    public Guid InvoiceLineId { get; set; }
    public Guid InvoiceId { get; set; }
    public virtual Invoice Header { get; set; }
}

so converting my old code from EF4 Model to POCO, I am supposed to add new Invoice and Lines. I used to create the master class and add the details to the instance of the master class itself.

var inv = new Invoice();
inv.InvoiceId = Guid.NewGuid();
var db = new InvoiceContext();
db.Invoices.Add(inv);
var invLine = new InvoiceLine();开发者_JAVA技巧
invLine = InvoiceLineId = Guid.NewGuid();
inv.Lines.Add(invLine);

inv.Lines <== is null at this point, so I cannot add a line to the instance of the invoice itself am I supposed to create a collection of InvoiceLines and set it, or is there some other way to do this.

So in short, how I can add master/detail rows to my database using POCO Code Only (CTP5).


Here is one way to do this:

using (var db = new Ctp5Context())
{
    var inv = new Invoice() 
    { 
        InvoiceId = Guid.NewGuid() 
    };
    var invLine = new InvoiceLine() 
    { 
        InvoiceLineId = Guid.NewGuid(),
        Header = inv
    };

    db.InvoiceLines.Add(invLine);
    db.SaveChanges();      
}

If you prefer to add an invoice object then:

using (var db = new Ctp5Context())
{
    var invLine = new InvoiceLine() 
    { 
        InvoiceLineId = Guid.NewGuid()          
    };
    var inv = new Invoice()
    {
        InvoiceId = Guid.NewGuid(),
        Lines = new List<InvoiceLine>() { invLine}
    };

    db.Invoices.Add(inv);
    db.SaveChanges();      
}

While all these works, I recommend always initialize the collection of navigation property in the class constructors so that you don't need to do it in the client code every single time as well as there is no chance of hitting NullReferenceException in the runtime:

public class Invoice
{
    public Invoice()
    {
        Lines = new List<InvoiceLine>();
    }
    public Guid InvoiceId { get; set; }
    public virtual ICollection<InvoiceLine> Lines { get; set; }
}

...

using (var db = new Ctp5Context())
{
    var invLine = new InvoiceLine() 
    { 
        InvoiceLineId = Guid.NewGuid()          
    };
    var inv = new Invoice()
    {
        InvoiceId = Guid.NewGuid(),         
    };
    inv.Lines.Add(invLine);

    db.Invoices.Add(inv);
    db.SaveChanges();      
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜