Nic*_*ias 1 c# left-join ef-code-first entity-framework-6
预先感谢您的帮助.我对使用Entity Framework 6include()方法时遇到的情况感到有些困惑.据我所知,include方法的作用就像封闭的对象一样,当对象匹配时也是如此.LEFT JOINNULLOUTER 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; }
}
Run Code Online (Sandbox Code Playgroud)
以下是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");
}
}
Run Code Online (Sandbox Code Playgroud)
在使用以下代码块时发生了不明确的情况:
var db = new BookingContext ();
var bookings = db.Bookings.Include (b => b.SourceBooking);
Run Code Online (Sandbox Code Playgroud)
我往往因为结果记录没来,其SourceBooking是NULL,在这种情况下LEFT JOIN会进行.
有人可以向我解释一下,并给我一个可能的解决方案吗?
谢谢.
EF产生LEFT OUTER JOIN了可选的关系,并INNER JOIN为需要的关系.
通过int在这里使用非可空类型
public int SourceBookingId { get; set; }
Run Code Online (Sandbox Code Playgroud)
你告诉EF这种关系是必需的,即列值不能,NULL并且SourceBooking表中必须始终有匹配的记录.因此它产生了INNER JOIN.
如果不是这样,只需将FK属性类型更改为可为空即可
public int? SourceBookingId { get; set; }
Run Code Online (Sandbox Code Playgroud)