我想一次添加2个实体



我想一次添加2个实体。当我想添加报价时,请同时添加报价细节。但是,让我们在报价中添加更多细节。我做不到。如果你能帮忙,我会很高兴的。

public class Offer
{
public int Id { get; set; }
public int CompanyId { get; set; }
public int CompanyContactId { get; set; }
public int OfferNumber { get; set; }
public string Annotations { get; set; }
public string CommercialConditions { get; set; }
public string TimeInformation { get; set; }
public decimal ProfitRate { get; set; }
public DateTime Date { get; set; }
public DateTime ValidityDate { get; set; }  

public Currency Currency { get; set; } 
public Status Status { get; set; }

//Navigation Property
public virtual Company Company { get; set; }
public virtual CompanyContact CompanyContact { get; set; }
public virtual List<OfferDetail> OfferDetail { get; set; }

public class OfferDetail
{
//public int Id { get; set; }
public int OfferId { get; set; }
public int RowNumber { get; set; }
public int Quantity { get; set; }
public string Description { get; set; }
public decimal UnitPrice { get; set; }
public decimal TotalPrice { get; set; }
public string Definition { get; set; }
public Boolean Optional { get; set; }
public decimal UnitProfit { get; set; }
public decimal UnitCost { get; set; }
//public Currency Currency { get; set; }
//Navigation Properties
public Offer Offer { get; set; }

当我向数据库添加报价表时,也添加了报价详细信息。但是让我们在引用中添加另一个细节。

public async Task<Result> AddOffer(OfferInfo offerInfo)
{
try
{
var vOffer = new Offer
{

Id = offerInfo.Id,
CompanyId = offerInfo.CompanyId,
CompanyContactId = offerInfo.CompanyContactId,
OfferNumber = offerInfo.OfferNumber,
Annotations = offerInfo.Annotations,
CommercialConditions = offerInfo.CommercialConditions,
TimeInformation = offerInfo.TimeInformation,
ProfitRate = offerInfo.ProfitRate,
Date = offerInfo.Date,
ValidityDate = offerInfo.ValidityDate,

}; _context.Offers.Add(vOffer);
await _context.SaveChangesAsync();

return Result.PrepareSuccess();
}
catch (Exception vEx)
{
return Result.PrepareFailure(vEx.Message);
}
}

我可以从我在这里创建的模型中添加。

这样我想把两个都加起来。提前谢谢。

如果您将OfferDetail的列表分配给Offer的详细信息实体将自动添加到适当的表中。

应该是这样的:

var vOffer = new Offer
{
// set all your properties of offer here
OfferDetails = new [] 
{
new OfferDetail {/*init details here*/}, 
// you can add more of details objects here 
} 
}

鸡和蛋的问题,但有一个解决方案,如果你在OfferDetail中定义需要Offer的构造函数,然后将自己添加到List<OfferDetail>

public class Offer
{
public Offer()
{
OfferDetail = new List<OfferDetail>();
}
//Navigation Property
public List<OfferDetail> OfferDetail { get;  }
}
public class OfferDetail
{
public OfferDetail(Offer offer)
{
Offer = offer;
offer.OfferDetail.Add(this);
}
public int OfferId { get => Offer.Id; }
//Navigation Properties
public Offer Offer { get; }
}

最新更新