实体框架中POCO类之间的关系,代码优先

时间:2013-04-07 11:12:09

标签: entity-framework entity-framework-4.1 entity-relationship

我重新实现了SimpleMembershipProvider自动创建的数据库。实际上我有一个关于2个表链接的问题:

create table user_profiles
(
  id       int not null identity, /* PK */
  username varchar(128) not null,
  .........
);

create table membership
(
  userid int not null,   /* FK to user_profile. */
  ..............
);

我想创建初始POCO类之间的关系:

public class UserProfile : BaseType
{
    public virtual Membership Membership { get; set; }
    ......
    public string UserName { get; set; }
    ......
}

public class Membership
{
    public virtual int UserId { get; set; }
    public virtual UserProfile User { get; set; }
    ......
}

在用作PK的Membership属性UserId中,与数据库中的FK同时使用。我尝试了以下配置:

public class UserProfileConfiguration : EntityTypeConfiguration<UserProfile> {
    public UserProfileConfiguration() {
        HasKey(k => k.Id);
        Map(m => m.ToTable("user_profiles"));

        HasRequired(t => t.Membership)
            .WithRequiredPrincipal(t1 => t1.User)
            .Map(m => m.MapKey("userid"));
        ....
    }
}

public class MembershipConfiguration : EntityTypeConfiguration<Membership> {
    public MembershipConfiguration() {
        HasKey(k => k.UserId);
        Map(m => m.ToTable("webpages_Membership"));

        //Property(x => x.UserId).HasColumnName("userid");
    }
}

MembershipConfiguration中的行注释掉(如示例中)命令Add-Migration在迁移命令中创建2条记录时:

c => new {
  UserId = c.Int(nullable: false, identity: true),
  .............
  userid = c.Int(nullable: false),

如果我取消注释,则命令失败并显示错误消息Each property name in a type must be unique. Property name 'userid' was already defined.

我如何声明所需的结果,同时使用'userid'列作为PK和FK?

0 个答案:

没有答案