小编chr*_*229的帖子

通过EF插入后获取自动身份密钥

在通过Entity Framework 4.1添加记录时,是否有直接的方法来检索数据库自动生成的主键?

例如:

dbcontext.Entity_Tables.Add(new Entity_Table { item1 = val1, item2 = val2 });
dbcontext.SaveChanges();
newPK = ???;
Run Code Online (Sandbox Code Playgroud)

SQL等价物将是:

newPK = executeOnDB("INSERT INTO Entity_Table (item1, item2) VALUES (val1, val2);SELECT @@Indentity";);
Run Code Online (Sandbox Code Playgroud)

顺便说一下,我使用的是MySQL,但SQL与MSSQL上的相同

entity-framework entity-framework-4.1 dbcontext

46
推荐指数
1
解决办法
6万
查看次数

具有Auto-Id的实体框架外键插入

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

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;}
}
Run Code Online (Sandbox Code Playgroud)

user_id是SQL Server的User和User_Profile表中的PK.它还在User表中设置为Identity列.

当我尝试通过EFDBContext Add/SaveChanges插入新记录时.我收到以下错误:"User_rofile表中的user_id不能为NULL"这非常有意义,因为这是一个PK列.我希望EF能够从用户获取Identity user_id并在保存时将其插入User_Profile user_id.

这是可能的,如果是这样,我将如何实现?

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

c# entity-framework ef-code-first entity-framework-4.1

7
推荐指数
1
解决办法
1万
查看次数

实体框架映射到查找表

我有3个表需要与实体框架映射,我不知道正确的方法来解决这个问题.这是我的3个实体:

public class User
{
   [Key] 
   public int user_id {get; set;}
   public string user_name {get; set;}

   public virtual List<Role> roles {get; set;}
}

public class Role
{
   [Key] 
   public int role_id {get; set;}

   public string role_name {get; set;}
}

public class User_Role
{
   [Key] 
   public int user_role_id {get; set;}

   public int user_id {get; set;}
   public int role_id {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

请注意,User_Role实体只表示一个查找表,用于将多个角色链接到单个用户.

使用SQL我会做类似的事情:

SELECT User.user_name, Role.role_name FROM User INNER JOIN User_Role ON User_Role.user_id = User.user_id INNER JOIN Role ON Role.role_id = …
Run Code Online (Sandbox Code Playgroud)

mapping lookup entity-framework inner-join entity-framework-4

4
推荐指数
1
解决办法
1688
查看次数