为简洁起见,删除了一些代码。
我使用Entity Framework Core创建了一个ASP.NET Core MVC网站。
我有Parts
,Distributors
和DistributorParts
(联接表)的三个表格。在我的网站上,我有一个页面可以将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;
}