简体   繁体   English

使用 Entity Framework 6 将父实体与数据库中现有的子实体连接起来

[英]Connect parent entity with existing child entity in database using Entity Framework 6

I'm using Entity Framework 6 to design and use a database that has a child Table of users which looks like this:我正在使用 Entity Framework 6 来设计和使用一个数据库,该数据库具有一个子用户表,如下所示:

public class User
{
    public long Id { get; set; }
    public string UserName { get; set; }
    public string CompanyId { get; set; }
}

And an Order table that looks like this:还有一个如下所示的 Order 表:

    public class Order
{
    public long OrderId { get; set; }
    public int ItemCount { get; set; }
    public DateTime OrderDate{ get; set; }
    ...

    public virtual User User { get; set; }

}

In my database, the field representing the User table in Order table is User_Id在我的数据库中,表示 Order 表中 User 表的字段是User_Id

Now my issue here (which might be a database design issue) is that before Creating a new User and Order in the database, I want to check if the user exists, and if he does, link it to the new order instead of creating a new User.现在我的问题(可能是数据库设计问题)是在数据库中创建新用户和订单之前,我想检查用户是否存在,如果存在,将其链接到新订单而不是创建新用户。 I have a method that Adds new user if the user doesn't exist and returns either the created or the existing user's Id field value.如果用户不存在,我有一个添加新用户的方法,并返回创建的或现有用户的Id字段值。

How to Create a new instance of Order that takes the Id value instead of User object to avoid having duplicate users, or is there a better way to handle this Use Case?如何创建一个新的 Order 实例,它采用Id值而不是User object 以避免重复用户,或者是否有更好的方法来处理这个用例?

I tried to return the object instead of the UserId, but it saves a new User in the User Table我试图返回 object 而不是 UserId,但它在用户表中保存了一个新用户

Not sure if this answers your problem.不确定这是否能解决您的问题。 But this way should ensure that you don't create another user object, but instead retrieves a user object from db.但是这种方式应该确保您不会创建另一个用户 object,而是从 db 中检索用户 object。

 public class UserHandler
    {
        //Use dbcontext instead to get a user list
        public List<User> UserList = new List<User>();
        public void handleUserList(int id)
        {
            User oneUser = UserList.FirstOrDefault(n => n.id==id);
            if (oneUser.Equals(null))
            {
                oneUser = new User();
                //Functionality to save the user information
            }
        }
    }

Another tip is to use data annotations for properties to make sure they will act the way you want.另一个技巧是对属性使用数据注释,以确保它们按照您想要的方式运行。

public class Order
{
    [Key]
    public long OrderId { get; set; }
    public int ItemCount { get; set; }
    public DateTime OrderDate{ get; set; }
    ...

    public virtual User User { get; set; }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM