[英]Include() is not working as LEFT JOIN (Entity Framework 6)
预先感谢您的帮助。 我对使用include()
方法Entity Framework 6时发生的情况感到有些困惑。 据我了解,当封闭对象为NULL
时,include方法可以用作LEFT JOIN
,而当对象具有匹配项时,可以用作OUTER JOIN
。
我将向我传递发生的示例,以便您帮助我了解发生的情况。
我的桌子上有以下模型:
public class Booking
{
[Key]
public int ID{ get; set; }
public string Description{ get; set; }
public decimal Amount{ get; set; }
public decimal AmoutPaid{ get; set; }
public DateTime? Checkin { get; set; }
public DateTime? Checkout { get; set; }
[ForeignKey("SourceBooking ")]
public int SourceBookingId { get; set; }
public SourceBooking SourceBooking { get; set; }
}
public class SourceBooking
{
[Key]
public int ID{ get; set; }
public string Name{ get; set; }
public decimal CommissionFee{ get; set; }
}
以下是DbContext
:
public class BookingContext:DbContext
{
public BookingContext():base("bookingConnection")
{
}
public DbSet<Booking> Bookings{ get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SourceBooking>().ToTable("sourcebookings", "public");
modelBuilder.Entity<Booking>().ToTable("bookings", "public");
}
}
使用以下代码块时发生的情况尚不清楚:
var db = new BookingContext ();
var bookings = db.Bookings.Include (b => b.SourceBooking);
我倾向于,因为在结果中没有出现SourceBooking
为NULL
的记录,在这种情况下将进行LEFT JOIN
。
有人可以向我解释一下,并给我这种情况的可能解决方案吗?
谢谢。
EF为可选关系生成LEFT OUTER JOIN
,为所需关系生成INNER JOIN
。
通过在此处使用不可为空的int
类型
public int SourceBookingId { get; set; }
您告诉EF这是必需的关系,即列值不能为NULL
并且SourceBooking
表中必须始终有匹配的记录。 因此,它生成INNER JOIN
。
如果不是这种情况,只需将FK属性类型更改为nullable
public int? SourceBookingId { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.