2 回答
TA贡献1155条经验 获得超0个赞
您确实不需要在 Linq 中加入任何关系来建立关系。您只需要在模型中定义您的关系(生成器会自动为您执行此操作,前提是您已在数据库本身中设置了关系 - 或者您直接在模型中执行此操作,例如首先使用代码)。以下示例展示了为什么不需要它,以及如何使用导航属性(基于 MS SQL Northwind 示例数据库):
string defaultConString = @"server=.\SQLExpress2012;Database=Northwind;Trusted_Connection=yes;";
void Main()
{
var ctx = new MyContext(defaultConString);
var customerId = "FISSA";
var customer = ctx.Customers
.Include(c => c.Orders)
.SingleOrDefault(c => c.CustomerId == customerId);
if (customer != null)
{
Console.WriteLine($"{customer.CompanyName}, Orders: {customer.Orders.Count()}");
// var frmMusteriSiparisleri = new Form { Text = string.Format("[{0}] - Siparisler", customerId) };
// var dgvSiparisler = new DataGridView { Dock = DockStyle.Fill, ReadOnly = true, DataSource = customer.Orders.ToList() };
// frmMusteriSiparisleri.Controls.Add(dgvSiparisler);
// frmMusteriSiparisleri.ShowDialog();
}
}
public class MyContext : DbContext
{
public MyContext(string connectionString)
: base(connectionString)
{ }
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
public DbSet<Product> Products { get; set; }
}
public class Customer
{
[Key]
public string CustomerId { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
// ...
public virtual List<Order> Orders { get; set; }
}
public class Order
{
[Key]
public int OrderId { get; set; }
public string CustomerId { get; set; }
public DateTime OrderDate { get; set; }
public DateTime? ShippedDate { get; set; }
[ForeignKey("CustomerId")]
public Customer Customer { get; set; }
public virtual List<OrderDetail> OrderDetails { get; set; }
}
[Table("Order Details")]
public class OrderDetail
{
[Key]
[Column(Order = 1)]
public int OrderId { get; set; }
[Key]
[Column(Order = 2)]
public int ProductId { get; set; }
public decimal UnitPrice { get; set; }
public Int16 Quantity { get; set; }
[ForeignKey("ProductId")]
public Product Product { get; set; }
[ForeignKey("OrderId")]
public Order Order { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
// ...
}
TA贡献1786条经验 获得超13个赞
您需要左连接和DefaultIfEmpty
方法,如下所示:
var query = from l in context.Loan
join lp in context.LoanPayment on l.Id equals lp.LoanId into j1
from lp in j1.DefaultIfEmpty()
select new { Loan = l, LoanPayment = lp == null ? "(No LoanPayment)"
: lp.Id.ToString() };
或者,如果您想选择 的整个对象LoanPayment:
select new { Loan = l, LoanPayment = lp ?? new loanPayment() };
- 2 回答
- 0 关注
- 98 浏览
添加回答
举报