C# 具有自动Id的实体框架外键插入

C# 具有自动Id的实体框架外键插入,c#,entity-framework,entity-framework-4.1,ef-code-first,C#,Entity Framework,Entity Framework 4.1,Ef Code First,我有2个实体用户和用户配置文件(一对一关系)。我把它们联系起来如下: 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 {g

我有2个实体用户和用户配置文件(一对一关系)。我把它们联系起来如下:

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是SQL Server的user和user_Profile表中的主键。它还被设置为用户表中的标识列

当我尝试通过EFDBContext Add/SaveChanges插入新记录时。我得到了以下错误:“user\u id不能在user\u Profile表中为NULL”这非常有意义,因为这是一个PK列。我希望EF能够从用户那里获取身份用户id,并在保存时将其插入到用户配置文件用户id中

这可能吗?如果可能,我将如何实施


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

您必须在.edmx文件中将StoreGeneratedPattern属性设置为Identity,以便让框架知道该字段是由数据库这个链接可能会有帮助


我认为有必要使用Fluent API明确地配置一对一关系:

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

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasRequired(u => u.user_profile)
            .WithRequiredPrincipal();
    }
}
有必要在其中一个类中将
DatabaseGeneratedOption
Identity
关闭到
None
。我已经交换了principal和dependent,因为似乎
用户应该是principal。
[ForeignKey(…)]
不是必需的,因为EF将
用户配置文件中的
用户id
识别为
用户的FK属性

像这样的代码

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

    user.user_profile = userProfile;

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

…应按预期工作,并将两个相关实体保存到数据库中。

我刚刚进行了搜索,但我的应用程序目录中没有.edmx文件。我正在使用EF4。我错过什么了吗?嗯,应该在那里。.edmx文件基本上就是您生成的模型,因此请查找具有该名称的文件。或者,您可以在解决方案资源管理器中右键单击该模型,然后用xml编辑器打开它。我找不到任何.edmx文件,我所拥有的最接近模型的是我创建的class.cs文件。请注意,我确实手动创建了DB表和类(使属性/列名相同),然后我只是实例化了DBContext并在web.config中建立了正确的连接。一切似乎都很好…除了上面的身份问题。啊,我想你至少使用了designer来生成映射。不幸的是,我不知道还有别的办法。如果你似乎不明白,那永远是一个选择。生成一个模型,导入表并关闭代码生成,这样您仍然可以使用实体/上下文类。谢谢你的帮助,萨阿德!哇!这正是你所说的。非常感谢Slauma!
using (var context = new MyContext())
{
    var user = new User();
    var userProfile = new User_Profile();

    user.user_profile = userProfile;

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