在插入具有Entity Framework的父项时插入从属实体

时间:2015-12-25 02:22:08

标签: entity-framework

插入父级时,我在插入依赖实体的记录时遇到问题。下面是我的实体定义和映射

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);
    }
}

在数据库模式中,所有表都有一个ID列,但在EBUserInfor类中,Id列是EBUsers表的主键和外键。

BaseEntityuMapping映射Id列并将DatabaseGenerationOptions设置为identity,但在EBUserinfoMapping类中,我使用DatabaseGenerationOption覆盖None EBUser

当我使用Entity Framework插入新的userInfo记录时,会创建用户记录但不会创建request.user记录

请帮忙

由于

1 个答案:

答案 0 :(得分:0)

将用户映射到userInfo

EBuser user= new EBuser();
// fill here user
EBuserInfo info = new EBuserInfo();
Info.userInfo= user;
// fill here rest info
db.add(info);
db.saveChanges();