C# ef core.Include().Contains()空引用异常

C# ef core.Include().Contains()空引用异常,c#,linq,entity-framework-core,C#,Linq,Entity Framework Core,我有我的模型这样设置 public class Model1 : IEquatable<Model1> { public int Model1Id { get; set; } public string Name1 { get; set; } public Model2 Model2 { get; set; } public int Model2Id { get; set; } public bool Equals(Model1 other)

我有我的模型这样设置

public class Model1 : IEquatable<Model1>
{
    public int Model1Id { get; set; }
    public string Name1 { get; set; }
    public Model2 Model2 { get; set; }
    public int Model2Id { get; set; }

    public bool Equals(Model1 other)
    {
        return this.Model2.Equals(other.Model2)
            && this.Name1 == other.Name1;
    }
}

public class Model2 : IEquatable<Model2>
{
    public int Model2Id { get; set; }
    public string Name2 { get; set; }

    public bool Equals(Model2 other)
    {
        return this.Name2 == other.Name2;
    }
}

public class ModelContext : DbContext
{
    public DbSet<Model1> Model1 { get; set; }
    public DbSet<Model2> Model2 { get; set; }
    public ModelContext(DbContextOptions<ModelContext> options) : base(options) { }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Model1>(b =>
        {
            b.HasOne(m1 => m1.Model2).WithMany().HasForeignKey(m1 => m1.Model2Id);
        });
    }
}
然后一切正常

编辑:


我的问题是。。。为什么我需要调用一个可计算的?我希望它在不调用numerable的情况下工作。

区别在于一个是entityframe工作调用,另一个是linq to Object 实体框架不理解CLR对象的包含

public void AddIfNotExists(Model1 model1)
{

    //No Need for the include this is executed in sql,  assuming the model 2 
    //property has already been included in your model1 this should work fine
    if(false == _context.Model1.Any(x => x.Name1 == model1.Name1 
                        && x.Model2.Name2 == model1.Model2.Name2))
    {
        _context.Model1.Add(model1);
    }
}

我根据您的逻辑进行了此操作,但您可能真的只想检查model1.id是否是model1集。但是我不知道你的架构在做什么,所以这可能是你想要的。asenumerab你的意思是AsEnumerable`请看编辑你到底想做什么毫无意义,是否要检查列表是否包含某些内容,或者是否希望完整列表在可变引用类型中实现IEquatable,但不覆盖Object。Equals类似于@PaoloGo-请您在问题中添加足够的代码,以便我可以复制、粘贴和运行您认为非常好的代码?我想我有答案给你,但我想先测试一下。我正在寻找一个新的方法。我更新了我的问题,以表明我正在尝试创建一个AddifyNotExists方法。a@PaoloGo这有用吗?如果是这样,您是否可以标记为正确
ctx.Model1.Include(m1 => m1.Model2).AsEnumerable().Contains(model1);
public void AddIfNotExists(Model1 model1)
{

    //No Need for the include this is executed in sql,  assuming the model 2 
    //property has already been included in your model1 this should work fine
    if(false == _context.Model1.Any(x => x.Name1 == model1.Name1 
                        && x.Model2.Name2 == model1.Model2.Name2))
    {
        _context.Model1.Add(model1);
    }
}