实体框架1:1映射外键

时间:2017-03-24 15:39:16

标签: entity-framework ef-code-first ef-migrations

我的实体AppUser有一个可选的UserProfile,UserProfile有一个必需的AppUser。我想互相拥有一把外键。

public class AppUser
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public UserProfile UserProfile { get; set; }
        public int? UserProfileId { get; set; }
    }

public class UserProfile
    {
        public int Id { get; set; }

        public string SomeUserProfileValue { get; set; }

        public AppUser AppUser { get; set; }
        public int AppUserId { get; set; }
    }

我得到了这个映射:

modelBuilder.Entity<AppUser>().HasOptional(x => x.UserProfile).WithRequired(x => x.AppUser)

这会生成以下迁移。我注意到AppUser没有外键到UserProfile。 UserProfile中的外键也是在UserProfile.Id上定义的......我希望它在UserProfile.AppUserId上。

public override void Up()
    {
        CreateTable(
            "dbo.AppUsers",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Name = c.String(),
                    UserProfileId = c.Int(),
                })
            .PrimaryKey(t => t.Id);

        CreateTable(
            "dbo.UserProfiles",
            c => new
                {
                    Id = c.Int(nullable: false),
                    SomeUserProfileValue = c.String(),
                    AppUserId = c.Int(nullable: false),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.AppUsers", t => t.Id)
            .Index(t => t.Id);

    }

所以我尝试更改映射配置,如下所示

modelBuilder.Entity<AppUser>().HasOptional(x => x.UserProfile).WithRequired(x => x.AppUser)
                .Map(c => c.MapKey("AppUserId"));

但是现在当我尝试添加迁移时,我收到错误:

AppUserId: Name: Each property name in a type must be unique. Property name 'AppUserId' is already defined.

这似乎抱怨我的模型中已经定义了一个字段AppUserId。

这就是我们定义实体的方式,我们总是同时包含class和id字段,为在不同情况下使用哪些实体提供了更大的灵活性。

所以我有点卡在这里......有没有办法让这个1:1双向关系,同时在模型中定义类和id字段? 为什么在AppUser表中没有生成可以为空的外键?

1 个答案:

答案 0 :(得分:0)

我自己通常会使用DataAnnotations找到更好的结果。所以:

public class AppUser
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public int? UserProfileId { get; set; }

    [ForeignKey = "UserProfileId"]
    public UserProfile UserProfile { get; set; }

}

public class UserProfile
{
    [Key]
    public int Id { get; set; }

    public string SomeUserProfileValue { get; set; }

    public int AppUserId { get; set; }

    [ForeignKey = "AppUserId"]
    public AppUser AppUser { get; set; }

}
相关问题