0

Check at the following Db Scripts:

CREATE TABLE tlogdata
(
    logentryid INT NOT NULL, -- PK
    [key] NVARCHAR(25) NOT NULL, -- PK
    value NVARCHAR(MAX) NOT NULL
)

CREATE TABLE tlogentry
(
    logentryid INT IDENTITY(1,1) NOT NULL, -- PK
    [message] NVARCHAR(4000) NOT NULL
)

tlogentrydata has a composite PK => logentryid and key. logentryid references tlogentry.logentryid column

Now what i want to do is to create my Model like this:

public class LogEntryData
{
    public string Key { get; set; }
    public string Value { get; set; }
}

public class LogEntry
{
    public int Id { get; set; }
    public string Message { get; set; }
    public List<LogEntryData> Data { get; set; } 
}

As you can see, LogEntryData does not contain the "LogEntryID" as a property. So my question is How can I map (using fluent API) those two classes into my tables? I don't know if it is even possible to tell EF that LogEntryData has a composite PK without exposing one of the columns as a public property (in this case LogEntryId does not exists on LogEntryData class but does exists on tlogentrydata table as logentryid column)

Thank you in advance!

rzumbado
  • 99
  • 6

1 Answers1

1

It's not possible. You always must expose the full key as properties in your model. The mapping could be achieved then by:

modelBuilder.Entity<LogEntryData>()
    .HasKey(led => new { led.LogEntryId, led.Key });

modelBuilder.Entity<LogEntry>()
    .HasMany(le => le.Data)
    .WithRequired()
    .HasForeignKey(led => led.LogEntryId);
Slauma
  • 175,098
  • 59
  • 401
  • 420
  • I end up adding the LogEntryId on the LogEntryData class and it worked fine. So thanks for the answer. – rzumbado Feb 27 '13 at 18:48