我首先遇到有关实体框架数据库中一对一关系的问题.
I am having issues regarding one to one relationship in entity framework database first.
我有两个表,一个用户表和一个用户详细信息表.
I have two tables, a user table and a user details table.
用户将包括登录信息,用户名,注册日期,并且userDetails将具有联系方式,网站等信息.在我的数据库中,我的user.id引用了userdetails.userId.两者都是主键.
user would consist of login info, username, date registered and the userDetails would have information such as contact information, website, etc. In my database My user.id references userdetails.userId. Both are primary keys.
例如.
User: Id [Primary Key (incremented)] Password Salt RegisteredDate UserDetails UserId [Primary Key (References User.Id)] Firstname Contact我的问题是我可以通过SQL Server添加记录,但是EF引发异常.
My issue is I can add records through SQL Server but EF throws an exception.
如何在EF 6中成功创建一对一关系?
How can I successfully create a one to one relationship in EF 6?
推荐答案尝试使用这样的模型:
public class User { public int Id { get; set; } //... //navigation property public UserDetail UserDetail { get; set; } } public class UserDetail { [Key,ForeignKey("User")] public int UserId { get; set; } //... //navigation property public User User { get; set; } }这正在使用数据注释.如果要使用 Fluent Api ,则可以覆盖通过您的上下文使用OnModelCreating 方法:
This is using Data Annotation. If you want to use Fluent Api, you could override the OnModelCreating method on your Context this way:
protected override void OnModelCreating(DbModelBuilder modelBuilder) { // Configure UserId as PK for UserDetail modelBuilder.Entity<UserDetail>() .HasKey(e => e.UserId); // Configure StudentId as FK for StudentAddress modelBuilder.Entity<User>() .HasOptional(u => u.UserDetail) // Mark UserDetail as optional for User .WithRequired(ud=> ud.User); // Create inverse relationship }记住加密密码字段.
更多推荐
一对一关系EF数据库优先
发布评论