在下面的“Then”步骤中,我在第行得到一个ObjectDisposedException
expectedPersons.ShouldAllBeEquivalentTo(actualPersons);
:
[Then(@"the following persons should be in the database")]
public void ThenTheFollowingPersonShouldBeInTheDatabase(Table table)
{
var expectedPersons = table.Rows.Select(expected => new Person
{
Id = int.Parse(expected["Id"]),
Name = expected["Name"],
Vorname = expected["Vorname"],
Adressen = specflowPersonenAdressen.Where(p => p.PersonId == int.Parse(expected["Id"])).ToList()
}).ToList();
var actualPersons = new List<Person>();
foreach (var row in table.Rows)
{
var queryCriteria = new PersonQueryCriteria
{
NameFilter = row["Name"],
VornameFilter = row["Vorname"]
};
actualPersons.AddRange(personWorkUnit.GetPersonen(queryCriteria));
}
expectedPersons.ShouldAllBeEquivalentTo(actualPersons);
}
}
方法
personWorkUnit.GetPersonen(...)
public ICollection<Person> GetPersonen(PersonQueryCriteria queryCriteria)
{
using (var context = this.unitOfWorkContextFactory.Create())
{
var personRepository = this.repositoryFactory.Create<IPersonRepository>(context);
return personRepository.GetPersons(queryCriteria).ToList();
}
}
personRepository.GetPersons(...)
看起来像这样:
public ICollection<Person> GetPersons(PersonQueryCriteria personQueryCriteria)
{
var query = this.Context.GetQuery<Person>();
query
.Include(q => q.Adressen)
.Include("Adressen.Adresse");
if (!string.IsNullOrEmpty(personQueryCriteria.NameFilter))
{
query = query.Where(p => p.Name == personQueryCriteria.NameFilter);
}
if (!string.IsNullOrEmpty(personQueryCriteria.VornameFilter))
{
query = query.Where(p => p.Vorname == personQueryCriteria.VornameFilter);
}
return query.ToList();
}
我特别介绍了导航属性,因为据我所知,EF使用的是延迟加载。
数据库如下所示:
模型如下所示:
public partial class Person
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Person()
{
this.Adressen = new HashSet<PersonAdresse>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Vorname { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PersonAdresse> Adressen { get; set; }
}
public partial class Adresse
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Adresse()
{
this.Personen = new HashSet<PersonAdresse>();
}
public int Id { get; set; }
public string Strasse { get; set; }
public string Ort { get; set; }
public int Plz { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PersonAdresse> Personen { get; set; }
}
public partial class PersonAdresse
{
public int Id { get; set; }
public int PersonId { get; set; }
public int AdresseId { get; set; }
public virtual Adresse Adresse { get; set; }
public virtual Person Person { get; set; }
}
提前感谢