EntityFramework.Extensions 6.1 Batch Delete throws “Sequence contains more than one element”

折月煮酒 提交于 2019-12-11 09:04:32

问题


Trying to use EntityFramework.Extensions for Delete and I have a case where I get the error from the title. Here is the scenario:

public class AList
{
    [Key]
    public int Id { get; set; }

    [Column]
    public int XId { get; set; }
}

public abstract class X
{
    [Key]
    public int Id { get; set; }

    public ICollection<AList> TheAList { get; set; }
}

public class Y : X
{
    [Column("TheId")]
    public int? SomeId { get; set; }
}

public class Z : X
{
    [Column("TheId")]
    public int? SomeIdZ { get; set; }
}

This is the mapping:

modelBuilder.Entity<X>()
.HasKey(t => t.Id)
.Map<Y>(t => t.Requires("XType").HasValue(1))
.Map<Z>(t => t.Requires("XType").HasValue(2));

modelBuilder.Entity<X>()
.HasMany(t => t.TheAList)
.WithRequired()
.HasForeignKey(t => t.XId);

And this is what how I'm deleting the row:

db.XTable.Where(t => t.Id == Id).Delete();

What's wrong with my setup? It works fine when I do:

db.AListTable.Where(t => t.XId == Id).Delete();

回答1:


It might be a bug in EntityFramework.Extended, in which case you can:

  • report the bug (on https://github.com/loresoft/EntityFramework.Extended)
  • or wait for someone else to do it,
  • or check out the source code and try to fix it yourself
  • or use a workaround

possible workarounds:

// not ideal, because object(s) are fetched from db
// I assume that you use the library to prevent this situation.
var existing = db.XTable.SingleOrDefault(t => t.Id == Id);
if (existing != null)
   db.XTable.Remove(existing);

// without fetching the object from db
db.Database.ExecuteSqlCommand("DELETE [XTable] WHERE Id = @Id", new SqlParameter("Id", Id));

Either way, the situation sucks a bit ;)



来源:https://stackoverflow.com/questions/23386698/entityframework-extensions-6-1-batch-delete-throws-sequence-contains-more-than

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!