我有2张桌子
USERS
[Id] INT NOT NULL PK IDENTITY,
[FirstName] nvarchar,
[LastName] nvarchar
and ACCOUNTS
[Id] INT NOT NULL PK,
[Password] nvarchar,
CONSTRAINT FK_Accounts_Users FOREIGN KEY (Id) REFERENCES [security].[Users] (Id)
我需要同时添加用户和它的个人资料。
使用EF FulentApi我制作了这样的模型:
public UserConfiguration()
{
ToTable("Users", "Security");
HasKey(i => i.Id);
Property(i => i.Id).HasColumnName("Id");
Property(i => i.FirstName).HasColumnName("FirstName");
Property(i => i.LastName).HasColumnName("LastName");
HasRequired(i => i.Account).WithRequiredPrincipal(i => i.User);
}
public AccountConfiguration()
{
ToTable("Accounts", "Security");
HasKey(i => i.Id);
Property(i => i.Id).HasColumnName("Id");
Property(i => i.Password).HasColumnName("Password");
HasRequired(i => i.User).WithRequiredDependent();
}
然后,当我添加User with Account时,它允许我添加null Acount,即此代码将起作用
using(var db = new SecurityDbContext())
{
var user = db.Users.Add(new User
{
FirstName = "John",
LastName = "Rambo"
});
db.SaveChanges();
}
为什么Account为null,如果在我的UserConfiguration模型中,我根据需要设置了帐户?
然后我怎么能建立用户与帐户1:1的关系?
提前致谢。