EF Code First CTP4 - 是否支持一对一关系? [英] EF Code First CTP4 - Are one to one relationships supported?
问题描述
我有以下实体:
公共类用户
{
public int UserId {get;组; }
public string用户名{get;组; }
公开个人资料{get;组; }
}
公共类简介
{
public string FirstName {get;组; }
public string LastName {get;组; }
public string PostalCode {get;组; }       
}
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string PostalCode { get; set; }
}
是否可以将此工作映射到两个表:
is it possible to get this working mapping to two tables:
用户(UserId(PK),用户名)
Users(UserId (PK), Username)
配置文件(UserId(FK + PK),FirstName,LastName,PostCode)
Profiles(UserId (FK + PK), FirstName, LastName, PostCode)
推荐答案
您好,
所有类都需要公开主键属性,因此您需要添加一个Profile.UserId属性。完成后,您可以按如下方式映射关系:
All classes need to expose a primary key property, so you would need to add a Profile.UserId property. Once you have done that you can map the relationship as follows:
public class ProfileContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Profile> Profiles { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Profile>()
.HasKey(p => p.UserId);
modelBuilder.Entity<User>()
.HasOptional(u => u.Profile)
.WithRequired()
.HasConstraint((u, p) => u.UserId == p.UserId);
}
}
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PostalCode { get; set; }
}
这篇关于EF Code First CTP4 - 是否支持一对一关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!