我在使用 EF 时遇到问题,当我获取包含关联活动列表的所有条目时。 那么只有最后一个条目引用了特定的活动,该活动在其活动列表中。
例如
Entry1
有一个列表,其中包括 Activity1
Entry2
有一个列表,其中包括 Activity1
Entry2
包含 Acivity1
,而不是两者都包含我有以下 EF 配置
public class WeeklyReviewBlazorClientDbContext : WeeklyReviewDbContext
{
public WeeklyReviewBlazorClientDbContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(WeeklyReviewBlazorClientDbContext).Assembly);
}
}
// Program.cs
builder.Services.AddDbContext<WeeklyReviewBlazorClientDbContext>(options =>
{
//options.UseLazyLoadingProxies();
options.UseInMemoryDatabase(databaseName: "WeeklyReview");
});
问题出在以下方法
public IEnumerable<EntryModel> GetAll()
{
return _db.Entry.Include(x => x.Activities).Where(x => x.UserGuid == UserGuid).ToList();
return _db.Entry.Include(x => x.Activities).Where(x => x.UserGuid == UserGuid).AsNoTracking().ToList(); // Also tried this
}
它没有返回我期望的结果。 下面的测试用例说明了我的意思。
public void Test()
{
var aBreakfast = new Activity("Breakfast");
var aDinner = new Activity("Dinner");
AddEntry(aBreakfast);
var entries1 = GetAll(); // Retrives one entry with a Breakfast Activity
AddEntry(aDinner);
var entries2 = GetAll(); // Retrives two entries first with a Breakfast and second with a Dinner Activity
AddEntry(aBreakfast);
var entries3 = GetAll(); // Retrives three entries first without the Breakfast, second with Dinner and the last with the Breakfast Activity
// This should have returned a Breakfast, Dinner and a Breakfast
}
public void AddEntry(ActivityModel activity)
{
var entry = new EntryModel(_timeService.Current, new List<ActivityModel>(), UserGuid);
_db.Entry.Add(entry);
entry.Activities = new List<ActivityModel>() { activity };
}
这两个型号是:
public class ActivityModel
{
public int Id { get; set; }
public string Name { get; set; }
public string NormalizedName { get; set; }
public bool Deleted { get; set; }
public CategoryModel Category { get; set; }
public Guid UserGuid { get; set; }
}
public class EntryModel
{
public int Id { get; set; }
public DateTime StartTime { get; set; }
public DateTime? EndTime { get; set; }
public DateTime RecordedTime{ get; set; }
public TimeSpan Duration => EndTime.HasValue ? EndTime.Value - StartTime : TimeSpan.Zero;
public List<ActivityModel> Activities { get; set; } // Also tried
public bool Deleted { get; set; }
public Guid UserGuid { get; set; }
}
我认为这与重复键有关,因为早餐活动由两个条目引用,因此最后一个条目是唯一能够引用它的条目。 因为第一个条目引用了早餐活动。
为了更好地了解上下文,您可以查看这里。
在您的 AddEntry 方法中,您应该将活动 add 到已存在的活动列表中。所以你的代码应该是:
public void AddEntry(ActivityModel activity)
{
//I don't think this line of your code works, because there would be a constructor:
var entry = new EntryModel(_timeService.Current, new List<ActivityModel>(), UserGuid);
entry.Activities.Add(activity);
_db.Entry.Add(entry);
}