繁体   English   中英

实体框架代码优先:一对一,其中PK是FK

[英]Entity Framework Code First: One-to-One where PK is a FK

我想使用Entity Framework 5 Code First映射一对一关系,如下所示:

public class User
{
     public Guid Id { get; set; }
}

public class Profile
{
     public User Owner { get; set; }
}

请注意,数据库配置文件表架构具有一个主键 UserId ,它是Users表的外键

我想知道是否可以避免在Profiles表中使用人为标识符

先感谢您!



UPDATE

好吧,看来Erangahvd的答案都有用。 做出了自己的贡献,我成功地创建了一个事务,该事务具有所属个人资料。

  • hvd => 对象模型中不需要人工标识符
  • Erlanga =>您的方法有效,但会强制您在数据库中具有[Id]列

有人在数据库表中找到避免人工识别符的方法吗?

使用流畅的API来映射关系。

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     modelBuilder.Entity<Profile>()
        .HasRequired(p => p.Owner)
        .WithOptional();
 }

更新:

一对一关系只能使用称为“共享主键”的映射技术进行建模。 即从属实体的PK也是FK。 在依赖实体(即Profile )中没有人为的标识符 ,因为它是指独立实体(即User )的PK值。

我就是这样做的(重命名类以符合您的情况):

public class User
{
    public Guid Id { get; set; }
    public Profile Profile { get; set; }
}

public class Profile
{
    public Guid OwnerId { get; set; }
    public User Owner { get; set; }
}

var userConfiguration = modelBuilder.Entity<User>();
userConfiguration.HasKey(u => u.Id);
userConfiguration.HasOptional(u => u.Profile).WithRequired(p => p.Owner);

var profileConfiguration = modelBuilder.Entity<Profile>();
profileConfiguration.HasKey(p => p.OwnerId);
profileConfiguration.HasRequired(p => p.Owner).WithOptional(u => u.Profile);

HasOptional(u => u.Profile).WithRequired(p => p.Owner)告诉EF p.Owner应该映射到主键OwnerId 应该能够在没有OwnerIdProfile属性的情况下进行这项工作,但这对我来说是可行的,并允许对这些属性进行进一步的配置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM