EF6具有导航属性的一对多fluent api
本文关键字:一对多 fluent api 属性 导航 EF6 | 更新日期: 2023-09-27 18:00:22
我正在尝试使用EF6和fluent API为我的实体应用一对多,但不断出现以下错误:
EmailTemplate_Attachments_Source_EmailTemplate_Attahments_Target::关系约束中"从属角色"answers"主体角色"中的属性数必须相同。
这些是我的型号:
public class EmailTemplate
{
public EmailTemplate()
{
Attachments = new List<EmailTemplateAttachment>();
}
public int EmailTemplateId { get; set; }
public int OperatorId { get; set; }
public EmailTemplateType MailType { get; set; }
public int LanguageId { get; set; }
public string Subject { get; set; }
public string Content { get; set; }
public string FromEmail { get; set; }
public DateTime CreationDate { get; set; }
public virtual ICollection<EmailTemplateAttachment> Attachments { get; set; }
}
public class EmailTemplateAttachment
{
public int EmailTemplateAttachmentId { get; set; }
public string ShortDescription { get; set; }
public string FilePath { get; set; }
public int EmailTemplateId { get; set; }
public virtual EmailTemplate EmailTemplate { get; set; }
}
这些是实体配置
public EmailTemplateConfiguration()
{
ToTable("T_EMAILS");
HasKey(emailTemplate => new { emailTemplate.OperatorId, emailTemplate.MailType, emailTemplate.LanguageId });
HasMany(t => t.Attachments)
.WithRequired(a => a.EmailTemplate)
.HasForeignKey(a => a.EmailTemplateId);
Property(emailTemplate => emailTemplate.EmailTemplateId).HasColumnName("row_id")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(emailTemplate => emailTemplate.OperatorId).HasColumnName("operator_id");
Property(emailTemplate => emailTemplate.MailType).HasColumnName("mail_type");
Property(emailTemplate => emailTemplate.LanguageId).HasColumnName("language_id");
Property(emailTemplate => emailTemplate.Subject).HasColumnName("subject");
Property(emailTemplate => emailTemplate.Content).HasColumnName("mail_content");
Property(emailTemplate => emailTemplate.FromEmail).HasColumnName("from_email");
Property(emailTemplate => emailTemplate.CreationDate).HasColumnName("insert_date");
}
public EmailTemplateAttachmentConfiguration()
{
ToTable("T_EMAILS_ATTACHMENTS");
HasKey(a => a.EmailTemplateAttachmentId);
HasRequired(a => a.EmailTemplate)
.WithMany(t => t.Attachments)
.HasForeignKey(a => a.EmailTemplateId);
Property(a => a.EmailTemplateAttachmentId).HasColumnName("attachment_id")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(a => a.ShortDescription).HasColumnName("short_description");
Property(a => a.FilePath).HasColumnName("file_url");
Property(a => a.EmailTemplateId).HasColumnName("mail_id");
}
我做错了什么?我已经尝试了很多次等待来配置外键,并一次又一次地获得相同的异常
在您的EmailTemplateConfiguration中,您定义EmailTemplate的主键是复合键:
HasKey(emailTemplate => new { emailTemplate.OperatorId, emailTemplate.MailType, emailTemplate.LanguageId });
但是在EmailTemplateAttachmentConfiguration中,您将依赖项配置为使用EmailTemplateId作为外键,这与您在上面定义的主键不同。外键应与主表主键相同。
此外,您还定义了两次EmailTemplate和EmailTemplateAttachment之间的关系(一次在EmailTemplateConfiguration中,另一次在电子邮件模板附件配置中)。它是多余的,一个就足够了