I am having an issue inserting a record for a dependent entity when inserting the parent. Below is my entity definitions and mappings
EBUser
public partial class EBUser : ModelBase, IUser<long>
{
public string UserName { get; set; }
public string Password { get; set; }
public long AccountId { get; set; }
public EBAccount EbAccount { get; set; }
public string Email { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? LastUpdateDate { get; set; }
public virtual EBUserInfo UserInfo { get; set; }
}
EBUserInfo
public partial class EBUserInfo : ModelBase
{
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string DisplayName { get; set; }
public virtual EBUser User { get; set; }
}
EBUserMapping
public class EBUserMapping : BaseEntityMapping<EBUser>
{
public EBUserMapping()
{
this.ToTable("Users");
this.Property(u => u.AccountId).HasColumnName("AccountId");
this.Property(u => u.Password).HasColumnName("Password");
this.Property(u => u.UserName).HasColumnName("UserName");
this.Property(u => u.Email).HasColumnName("Email");
this.Property(u => u.CreatedDate).HasColumnName("CreatedDate");
this.Property(u => u.LastUpdateDate).HasColumnName("LastUpdateDate").IsOptional();
//this.HasRequired(u => u.UserInfo).WithRequiredDependent(u => u.User);
this.HasRequired(t => t.EbAccount)
.WithMany(t => t.Users)
.HasForeignKey(d => d.AccountId);
}
}
EBUserInfoMapping
public class EBUserInfoMapping :BaseEntityMapping<EBUserInfo>
{
public EBUserInfoMapping()
{
this.ToTable("UserInfo");
this.Property(u => u.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(u => u.Email).HasColumnName("Email");
this.Property(u => u.FirstName).HasColumnName("FirstName");
this.Property(u => u.LastName).HasColumnName("LastName");
this.Property(u => u.DisplayName).HasColumnName("DisplayName");
// Relationships
this.HasRequired(t => t.User).//WithRequiredDependent(t => t.UserInfo);
WithOptional(t => t.UserInfo);
}
}
In the database schema, all tables have an ID column but in the EBUserInfor class the Id column is both the primary and foreign key to the EBUsers table.
The BaseEntityuMapping maps the Id column and set the DatabaseGenerationOptions to identity but in the EBUserinfoMapping class I overwrite that with a DatabaseGenerationOption of None.
When I insert a new EBUser record using Entity Framework, the user record is created but no userInfo record is created
Please help
Thanks
WithRequiredDependent(t => t.UserInfo)part? That's exactly the mapping you need here.this.HasRequired(t => t.User).WithRequiredDependent(t => t.UserInfo)(or WithOptional).