在我之前,一位开发人员首先使用了Entity Framework代码。我不擅长EF代码,所以当我尝试插入数据时,我的代码会出现这个错误:
Entities in 'TourismContext.HotelOrders' participate in the 'HotelOrder_Order' relationship. 0 related 'HotelOrder_Order_Target' were found. 1 'HotelOrder_Order_Target' is expected.
这是我的插入代码:
var hotelOrdersInsert = new Data.Entities.HotelOrder
{
OrderId = odr.ID // this gives 7
HotelID = 13,
StartAt = DateTime.Now, // arrivalDate,
EndAt = DateTime.Now, // departureDate,
PaymentTypeID = 1,
PaymentStatusID = 1,
PaymentIdentifier = "a",
TotalRate = Convert.ToDecimal(total),
CurrencyID = 1
};
db.HotelOrders.Add(hotelOrdersInsert);
db.SaveChanges();
这是我的HotelOrder
课程:
public class HotelOrder
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public int HotelID { get; set; }
public int OrderId { get; set; }
// other properties
public virtual Order Order { get; set; }
public virtual Hotel Hotel { get; set; }
}
这是我的Order
课程:
public class Order
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public virtual HotelOrder HotelOrder { get; set; }
}
在哪里可以找到订单和酒店订单模型之间的关系?
答案 0 :(得分:2)
问题是HotelOrder和Order之间的关系。您最有可能拥有1比1的关系。意思是,每个HotelOrder都必须有订单。
这种关系可能是在所谓的流利API中定义的。检查从DbContext派生的类的OnModelCreating(DbModelBuilder)函数覆盖。它可能陈述如下:
modelBuilder.Entity<HotelOrder>().HasRequired(hotel_order => hotel_order.Order).WithRequiredPrincipal();
这告诉EntityFramework每个HotelOrder必须有一个订单。
或者,可以将关系定义为DataAnnotations。就像埃尔文·马马多夫在答案中解释的那样。
此时解决方案变得明显。在将其添加到db.HotelOrders之前,您需要将一个Order实例添加到您的HotelOrder实例。
答案 1 :(得分:1)
您必须按如下方式编写此关系:
public class HotelOrder
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public int HotelID { get; set; }
[ForeignKey("Order")]
public int OrderId { get; set; }
public Order Order { get; set; }
[ForeignKey("Hotel")]
public int HotelId { get; set; }
public Hotel Hotel { get; set; }
}
public class Order
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public List<HotelOrder> HotelOrders { get; set; }
}