实体框架核心:在'加入'中添加新条目表删除现有记录

时间:2018-05-19 22:46:47

标签: c# asp.net-core entity-framework-core ef-core-2.0

为简洁起见,删除了一些代码。

我使用Entity Framework Core创建了一个ASP.NET Core MVC网站。

我有PartsDistributorsDistributorParts(联接表)的三个表格。在我的网站上,我有一个页面可以将Distributors添加到Part。当我为分销商1 第1部分创建新的DistributorPart记录时,会正确插入记录。但是,当我为分销商2 第1部分添加第二个DistributorPart记录时,第一个DistributorPart记录将被删除! (请注意,上述两个DistributorPart记录均使用第1部分

我的问题是:

  • 如何在不删除/影响现有记录的情况下插入新的DistributorPart条记录
  • 我做错了什么?

型号:

public class Part
{
    [key]
    public int Id { get; set; }

    public string Description { get; set; }

    public ICollection<DistributorPart> DistributorParts { get; set; }
}

public class Distributor
{
    [key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public ICollection<DistributorPart> DistributorParts { get; set; }
}

public class DistributorPart
{
    [key]
    public int Id { get; set; }

    public int OnHand { get; set; }

    public int OnOrder { get; set; }

    public int PartId { get; set; }

    public Part Part { get; set; }

    public int DistributorId { get; set; }

    public Distributor Distributor { get; set; }
}

这是我的DbContext

public class MyContext : DbContext
{
    public DbSet<Part> Parts { get; set; }

    public DbSet<Distributor> Distributors { get; set; }

    public DbSet<DistributorPart> DistributorParts { get; set; }

    public MyContext(DbContextOptions<MyContext> options) 
        : base(options) 
    { }
}

以下是插入新DistributorPart记录的代码:

public DistributorPart AddDistributorPart(DistributorPart distributorPart)
{
    var newDistributorPart = new DistributorPart
    {
        OnHand = distributorPart.OnHand,
        OnOrder = distributorPart.OnOrder,
        PartId = distributorPart.PartId,
        DistributorId = distributorPart.DistributorId
    };

    _context.Add(newDistributorPart);
    _context.SaveChanges();

    return newDistributorPart;
}

我可以在调试时在“应用程序输出”窗口中验证这一点:

  

Microsoft.EntityFrameworkCore.Database.Command:信息:已执行   DbCommand(1ms)[参数= [@ p0 =&#39;?&#39;,@ p1 =&#39;?&#39;,@ p2 =&#39;?&#39;],   CommandType =&#39; Text&#39;,CommandTimeout =&#39; 30&#39;] DELETE FROM   &#34; DistributorParts&#34;在哪里&#34; Id&#34; = @ p0; ...

修改

这是我调用AddDistributorPart()方法的Controller方法:

public DistributorPart AddDistributorToPart([FromBody] DistributorPart distributorPart)
{
    var part = _partService.GetPart(distributorPart.PartId);
    if (part == null || part.Id <= 0)
    {
        throw new Exception($"Part Id of {distributorPart.PartId} does not exist.");
    }

    var distributor = _distributorService.GetDistributor(distributorPart.DistributorId);
    if (distributor == null || distributor.Id <= 0)
    {
        throw new Exception($"Distributor Id of {distributorPart.DistributorId} does not exist.");
    }

    var userId = GetUserId();
    var newDistributorPart = _distributorPartService.AddDistributorPart(distributorPart, userId);

    ...

    return newDistributorPart;
}

0 个答案:

没有答案