简体   繁体   English

EF 将子实体添加到父实体

[英]EF adding child entity to parent entity

I'm trying to add a child entity to a parent entity.我正在尝试将子实体添加到父实体。 The child being User whilst the parent is CheckoutToken :孩子是User而父母是CheckoutToken

Inserting the CheckoutToken:插入 CheckoutToken:

 public async Task Insert(CheckoutToken model)
 {
    var checkoutToken = new Data.Models.CheckoutToken {
        Token = model.Token,
        License = _dbContext.Licenses.Single(l => l.Id == model.License.Id),
        Created = model.Created,
        Expires = model.Expires
    };

     checkoutToken.UserId = model.User.AspNetUserId;
     checkoutToken.User = await _userManager.FindByIdAsync(model.User.AspNetUserId);
     await _dbContext.CheckoutTokens.AddAsync(checkoutToken);
     await _dbContext.SaveChangesAsync();
 }

For some reason I get this exception:出于某种原因,我得到了这个例外:

Violation of PRIMARY KEY constraint 'PK_AspNetUsers'.违反 PRIMARY KEY 约束“PK_AspNetUsers”。 Cannot insert duplicate key in object 'dbo.AspNetUsers'.无法在对象“dbo.AspNetUsers”中插入重复键。 The duplicate key value is (73a0c19b-a7b1-4462-8e82-12be55e47002).重复的键值为 (73a0c19b-a7b1-4462-8e82-12be55e47002)。 The statement has been terminated.该语句已终止。

I don't understand why it's trying to create a user?我不明白它为什么要尝试创建用户?

try commented this line:尝试评论这一行:

public async Task Insert(CheckoutToken model)
 {
    var checkoutToken = new Data.Models.CheckoutToken {
        Token = model.Token,
        License = _dbContext.Licenses.Single(l => l.Id == model.License.Id),
        Created = model.Created,
        Expires = model.Expires
    };

     checkoutToken.UserId = model.User.AspNetUserId;
     // checkoutToken.User = await _userManager.FindByIdAsync(model.User.AspNetUserId);
     await _dbContext.CheckoutTokens.AddAsync(checkoutToken);
     await _dbContext.SaveChangesAsync();
 }

this because you try create new user with same data of an existing, if you need assign an existing user to an new entity only assign the Id of User not the full object这是因为您尝试使用现有用户的相同数据创建新用户,如果您需要将现有用户分配给新实体,只需分配用户的 Id 而不是完整对象

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

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