[英]Entity Type Configuration // Fluent API - mapping - zero to one foreignKey
I have a problem with mapping my classes using code first and Entity Type Configuration. 我在使用代码优先和实体类型配置映射类时遇到问题。
I have a class User 我有一个班级用户
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; }
which is a User Table. 这是一个用户表。 And a UserData - which will be a table contains UserData as Name, LastName etc.
还有一个UserData-将是一个表,其中包含UserData的名称,姓氏等。
I want to use UserId as Forgein Key one-to-zer-or-one. 我想使用UserId作为Forgein密钥一对一或一对。 For one user there will be only one UserData
对于一个用户,只有一个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; }
}
But can't quite figure out how to do the mapping 但是还不能弄清楚如何进行映射
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?
}
and the UserData 和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?
}
对于User
在UserConfiguration()
来映射一到零或一的关系可以定义为:
HasOptional(x => x.UserData).WithRequired(x => x.User);
For a 1:0..1 relationship in Entity Framework, the primary key for the optional side is also the foreign key, so you can set it up like this: 对于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
}
You can't have a separate primary key for UserData
. 您不能为
UserData
使用单独的主键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.