带有自动编号的实体框架外键插入 [英] Entity Framework Foreign Key Inserts with Auto-Id

查看:79
本文介绍了带有自动编号的实体框架外键插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个实体User和User_Profile(一对一关系)。我将它们链接如下:

 公共类用户
{
[Key]
[ForeignKey( user_profile)]
public int user_id {get; set;}

公共字符串用户名{get; set;}
公共字符串email {get; set; }

公共虚拟User_Proile user_profile {get; set;}
}


公共类User_Profile
{
[Key ]
public int user_id {get; set;}

public string firstname {get; set;}
public string lastname {get; set;}
}

user_id是SQL Server的User和User_Profile表中的PK。



当我尝试通过EFDBContext Add / SaveChanges插入新记录时,它也被设置为身份列。



我收到以下错误: User_Profile表中的user_id不能为NULL这是一个PK列,因此非常合理。我希望EF可以在保存时从Users中获取Identity user_id并将其插入User_Profile user_id中。



有可能吗?如果可以,我将如何实现?



更新:请注意,我手动创建了数据库表和代码类,因此无法通过.edmx文件访问StoreGeneratedPattern。

解决方案

我认为有必要使用Fluent API显式配置您的一对一关系:

 公共类MyContext:DbContext 
{
// ... ...您的DbSet

受保护的覆盖无效OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity< User>()
.HasRequired(u => u.user_profile)
.WithRequiredPrincipal();
}
}

以及实体类:

 公共类用户
{
[Key]
public int user_id {get; set;}
公共字符串用户名{get; set;}
公共字符串电子邮件{get; set;}
公共虚拟User_Profile user_profile {get; set;}
}

public类User_Profile
{
[键]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int user_id {get; set;}
public string firstname {get; set ;}
公用字符串姓氏{get; set;}
}

必须将 DatabaseGeneratedOption Identity 切换为 None 的课程。我已经交换了主体和从属关系,因为 User 应该是主体。不需要 [ForeignKey(...)] ,因为EF会识别中的 user_id User_Profile 作为 User 的FK属性。



像这样的代码...

 使用(var context = new MyContext())
{
var user = new User() ;
var userProfile = new User_Profile();

user.user_profile = userProfile;

context.Users.Add(user);
context.SaveChanges();
}

...应该可以正常工作,然后将两个相关实体保存到数据库。


I have 2 Entities User and User_Profile (one to one relationship). I have linked them as follows:

public class User
{
   [Key]   
   [ForeignKey("user_profile")]
   public int user_id {get;set;}

   public string username {get;set;}
   public string email {get;set;}

   public virtual User_Proile user_profile {get;set;}
}


public class User_Profile
{
   [Key]   
   public int user_id {get;set;}

   public string firstname {get;set;}
   public string lastname {get;set;}
}

user_id is a PK in both SQL Server's User and User_Profile tables. It is also set as an Identity column in the User table.

When I try to insert a new record via the EFDBContext Add/SaveChanges. I get the following error: "user_id cannot be NULL in the User_Profile table" This makes perfect sense as this is a PK column. I was hoping EF would be able to take the Identity user_id from Users and Insert it into User_Profile user_id when saving.

Is this possible and if so how would I implement that?

UPDATE: Please note that I manually created the DB tables and code classes so I dont have access to StoreGeneratedPattern via the .edmx file.

解决方案

I think it is necessary to configure your one-to-one relationship explicitely using Fluent API:

public class MyContext : DbContext
{
    // ... your DbSets

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasRequired(u => u.user_profile)
            .WithRequiredPrincipal();
    }
}

And the entity classes:

public class User
{
    [Key]   
    public int user_id {get;set;}
    public string username {get;set;}
    public string email {get;set;}
    public virtual User_Profile user_profile {get;set;}
}

public class User_Profile
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int user_id {get;set;}
    public string firstname {get;set;}
    public string lastname {get;set;}
}

It's necessary to switch off DatabaseGeneratedOption from Identity to None in one of the classes. I have swapped principal and dependent as it seems that the User should be the principal. The [ForeignKey(...)] is not necessary because EF will recognize user_id in User_Profile as a FK property to User.

A code like this...

using (var context = new MyContext())
{
    var user = new User();
    var userProfile = new User_Profile();

    user.user_profile = userProfile;

    context.Users.Add(user);
    context.SaveChanges();
}

...should work then as you expect and save both related entities to the database.

这篇关于带有自动编号的实体框架外键插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆