CTP5 POCO Code-Only,如何将主 - 详细记录添加到DB

时间:2011-01-28 15:16:15

标签: entity-framework-4 poco code-first entity-framework-ctp5

我正在尝试EF CTP5 POCO,并从EF4 EntityModel转换为POCO Code Only方法。

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; }
}

所以将我的旧代码从EF4 Model转换为POCO,我应该添加新的Invoice和Lines。我曾经创建了主类,并将细节添加到主类本身的实例中。

var inv = new Invoice();
inv.InvoiceId = Guid.NewGuid();
var db = new InvoiceContext();
db.Invoices.Add(inv);
var invLine = new InvoiceLine();
invLine = InvoiceLineId = Guid.NewGuid();
inv.Lines.Add(invLine);

inv.Lines&lt; ==此时为空,因此我无法在发票本身的实例中添加一行 我应该创建一个InvoiceLines的集合并设置它,或者还有其他方法可以做到这一点。

简而言之,我如何使用POCO Code Only(CTP5)将主/明细行添加到我的数据库。

1 个答案:

答案 0 :(得分:1)

以下是一种方法:

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();      
}

如果您希望添加发票对象,请:

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();      
}

虽然所有这些都有效,但我建议始终在类构造函数中初始化navigation属性的集合,这样你就不需要每次都在客户端代码中执行它,也就是没有机会在NullReferenceException中出现NullReferenceException。运行时:

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();      
}