我首先使用代码和实体类型配置来映射我的类。
我有一个用户类
public class User
{
public virtual UserData UserData { get; set; }
public Guid UserId { get; set; }
public string UserName { get; set; }
public virtual string PasswordHash { get; set; }
public virtual string SecurityStamp { get; set; }
public string Email { get; set; }
这是一个用户表。 UserData - 将是一个表包含UserData作为Name,LastName等。
我想将UserId用作Forgein Key one-to-zer-or-one。对于一个用户,将只有一个UserData
public class UserData
{
public long Id { get; set; }
public Guid UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual User User { get; set; }
}
但无法弄清楚如何进行映射
internal UserConfiguration()
{
ToTable("User");
HasKey(x => x.UserId)
.Property(x => x.UserId)
.HasColumnName("UserId")
.HasColumnType("uniqueidentifier")
.IsRequired();
... properties mapping
HasOptional(x => x.UserData).
WithRequired(x => x.User); ?? is this ok?
}
和UserData
internal UserDataConfiguration()
{
ToTable("UserData");
HasKey(x => x.Id)
.Property(x => x.Id)
.HasColumnName("Id")
.HasColumnType("bigint")
.IsRequired();
Property(x => x.FirstName)
.HasColumnName("FirstName")
.HasColumnType("nvarchar")
.HasMaxLength(255);
Property(x => x.LastName)
.HasColumnName("LastName")
.HasColumnType("nvarchar");
Property(x => x.UserId)
.HasColumnName("UserId")
.HasColumnType("uniqueidentifier")
.IsRequired();
?? is this ok?
}
答案 0 :(得分:1)
对于User
中的UserConfiguration()
来映射一对一或一对一关系,您可以将其定义为:
HasOptional(x => x.UserData).WithRequired(x => x.User);
答案 1 :(得分:1)
对于Entity Framework中的1:0..1关系,可选端的主键也是外键,因此您可以这样设置:
UserConfiguration()
{
ToTable("User");
HasKey(x => x.UserId)
Property(x => x.UserId)
.HasColumnName("UserId")
.HasColumnType("uniqueidentifier")
.IsRequired();
// you could define the relationship here as well, I moved it
// to UserDataConfiguration to make it easier to explain
// other properties
}
UserDataConfiguration()
{
ToTable("UserData");
HasKey(x => x.UserId);
Property(x => x.UserId)
.HasColumnName("UserId")
.HasColumnType("uniqueidentifier")
.IsRequired();
// This makes UserData's primary key the foreign key by default
HasRequired(x => x.User).WithOptional(x => x.UserData);
// other properties
}
UserData
无法使用单独的主键。