【发布时间】:2019-11-05 14:53:49
【问题描述】:
假设我想要一个有很多B 和很多A 的课程A;
我可以通过创建类AB,将ICollection<AB> ABs 字段添加到A 和B 类,然后通过ABs 类A 的属性访问B 来实现这一点。这有效。
但我想知道有没有办法直接从类A 访问相关的B 数据,而不是通过ABs 属性。
我会想出几种方法来做到这一点(我都没有设法开始工作):
public ICollection<B> Bs => this.ABs.Select(item => item.B).ToList();,但它没有,我有一个空异常,即使我在这个context.As.Include(item => item.ABs).ThenInclude(item => item.B);中包含ABs和Bs。ef core的fluent api(不知道怎么做)
using Microsoft.EntityFrameworkCore;
using System;
using Context;
namespace ConsoleApp1 {
class Program
{
static void Main(string[] args)
{
using var context = new ZContext();
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var A = context.As.Include(item => item.ABs).ThenInclude(item => item.B);
foreach (var a in A) {
Console.WriteLine(a.Bs);
}
return;
}
}
}
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Context
{
public class IDed
{
#region Constructors
public IDed()
{
ID = Guid.NewGuid();
}
#endregion
public Guid ID { get; set; }
}
public class A : IDed
{
public ICollection<AB> ABs { get; set; }
public ICollection<B> Bs {
get {
return ABs.Select(item => item.B).ToList();
}
}
}
public class B : IDed
{
public ICollection<AB> ABs { get; set; }
}
public class AB
{
#region Constructors
public AB()
{
}
public AB(A a, B b)
{
this.AID = a.ID;
this.BID = b.ID;
}
#endregion
public A A { get; set; } public Guid AID { get; set; }
public B B { get; set; } public Guid BID { get; set; }
}
public class ZContext : DbContext
{
public DbSet<A> As { get; set; }
public DbSet<B> Bs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=111.db3");
}
protected override void OnModelCreating(ModelBuilder mb)
{
#region Keys
mb.Entity<AB>().HasKey(item => new { item.AID, item.BID });
#endregion
#region Relations
// ???
#endregion
var a1 = new A();
var a2 = new A();
mb.Entity<A>().HasData(a1, a2);
var b1 = new B();
var b2 = new B();
mb.Entity<B>().HasData(b1, b2);
mb.Entity<AB>().HasData(
new AB(a1, b1),
new AB(a1, b2),
new AB(a2, b1),
new AB(a2, b2)
);
}
}
}
使用第一种方法我得到System.ArgumentNullException: 'Value cannot be null. (Parameter 'source')' 错误,即使我Include 和ThenInclude 都是相同的字段。
我意识到AB 类必须以任何方式保留,但这种配置是否可以实现,正确的做法是什么。
【问题讨论】:
标签: c# ef-core-3.0