一对一关系EF数据库优先

编程入门 行业动态 更新时间:2024-10-24 11:22:22
本文介绍了一对一关系EF数据库优先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我首先遇到有关实体框架数据库中一对一关系的问题.

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数据库优先

本文发布于:2023-11-14 13:52:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587393.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:关系   数据库   EF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!