I have some tables to specify standard email messages and the addresses from which they should be sent:
Email.Message
-------------
MessageId
Name
FromAddressId
Email.Address
-------------
AddressId
These tables are modeled in code using these classes:
public class EmailAddress
{
public int AddressId { get; set; }
}
public class EmailMessage
{
public int MessageId { get; set; }
public string Name { get; set; }
public int FromAddressId { get; set; }
public virtual EmailAddress FromAddress { get; set; }
}
var message = Db.EmailMessages
.Where(m => m.Name == name)
.Include(m => m.FromAddress)
.SingleOrDefault();
I am using Fluent API to specify the relationship:
internal class EmailMessageMap : EntityTypeConfiguration<EmailMessage>
{
public EmailMessageMap()
{
ToTable("Message", "Email");
HasKey(p => p.MessageId);
// What do I put here?
}
}
How do I set up the join to use the FromAddressId
of my EmailMessage
class? I've tried these options:
HasRequired(p => p.FromAddress).WithRequiredPrincipal(); // uses LEFT OUTER JOIN
HasRequired(p => p.FromAddress).WithRequiredDependent(); // uses INNER JOIN
These cause the SQL that gets created to use either a LEFT OUTER JOIN
or an INNER JOIN
, but they always try to join Message.MessageId
to Address.AddressId
, which is incorrect. How do I make it use the correct column (FromAddressId
)? I need to have something to replace the // What do I put here?
, because otherwise I get the following exception:
Invalid column name 'FromAddress_AddressId'
EDIT: I can place a [ForeignKey("FromAddressId")]
on top of the FromAddress
property and it works:
[Extent1].[FromAddressId] = [Extent2].[AddressId]
Progress! Now, how do I do this in Fluent API?