开发者

EF Code First: define one-to-many relationship with differing keys

I am having trouble defining a one-to-zero or many relationship between 2 entities in EF4.1.

Here is what my object model looks like:

public class SubmittedTransaction
{
    public int Batch_ID { get; set; }
    public Int64 Batch_Detail_ID { get; set; }
    public string Company_ID { get; set; }

    public virtual ICollection<SubmittedSplitTransaction> Splits { get; set; }
}

Using the fluent API, the above object has a composite PK defined as Batch_ID and Batch_Detail_ID.

public class SubmittedSplitTransaction
{
    public Int64 Batch_Detail_ID { get; set; }
    public string Company_ID { get; set; }
    public decimal Sales_Amount { get; set; }
    public decimal Revenue开发者_开发问答_Amount { get; set; }
}

Using the fluent API, the above object as a composite PK defined as Batch_Detail_ID and Company_ID.

This is mapped to an existing database (TPT).

The basic idea here is that a SubmittedTransaction can have zero to many SubmittedSplitTransactions associated to it. Navigation really only needs to be one way, from SubmittedTransaction to SubmittedSplitTransaction.

What is needed in my DBContext class (OnModelCreating override) or in my mapping classes for a lazy load to occur from SubmittedTransaction to SubmittedSplitTransaction?

Any help here would be very much appreciated!!!

[EDIT]

I have taken your advice and made the following changes:

public class SubmittedSplitTransaction
{
    public Int64 Batch_Detail_ID { get; set; }
    public string Company_ID { get; set; }
    public decimal Sales_Amount { get; set; }
    public decimal Revenue_Amount { get; set; }

    public virtual SubmittedTransaction SubmittedTransaction { get; set; }
}

In my DBContext class, I have added the following to the OnModelCreating override:

modelBuilder.Entity<SubmittedTransaction>().HasMany(s => s.Splits).WithRequired().Map(m => m.MapKey("Batch_Detail_ID"));

I must be missing something here because I am now getting the following exception thrown:

The specified association foreign key columns 'Batch_Detail_ID' are invalid. The number of columns specified must match the number of primary key columns.

A SubmittedTransaction has a key of Batch_ID and Batch_Detail_ID. It can have zero, one, or many SubmittedSplitTransactions, which has a key of Batch_Detail_ID and Company_ID. Rather than assuming conventions to create the relationship between these two objects, what configuration is required since what I have above is obviously wrong?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜