我对EF相对较新,我仍在学习过程中。我创建了一个存储库,从中我可以从数据库中获取数据。
我有以下类的结构:
public class Foo1 : CQA, IScorable
{
private double score;
public double Score
{
get
{
return score;
}
set
{
var t = Question; // this is where Question is always null
score = value;
}
}
protected Foo1() { }
public Foo1(CQ q, QO co) : base(question, new List<AO>())
{
}
}
public class CQA : Answer
{
public virtual IList<AO> AO { get; set; }
protected CQA() { }
public CQA(Question question, IList<AO> ao) : base(question)
{
AO = ao;
}
}
public class Answer : IEntity<int>
{
public virtual Question Question { get; set; } // This is null
public int Id { get; set; }
protected Answer() { }
public Answer(Question question)
{
Question = question;
}
}
映射表是:
public class AnswerMap : EntityTypeConfiguration<Answer>
{
public AnswerMap()
{
ToTable(nameof(Answer));
HasRequired(x => x.Question);
}
}
这是我从回购中获得的课程:
public abstract class Test : IEntity<int>
{
public int Id { get; set; }
public virtual IList<Answer> Answers { get; set; }
protected Test()
{
Answers = new List<Answer>();
}
public virtual Test AddAnswer(Answer answer)
{
var found = Answers.FirstOrDefault(l => l.Question.Id == answer.Question.Id);
if (found != null)
{
var index = Answers.IndexOf(found);
Answers.RemoveAt(index);
Answers.Insert(index, answer);
}
else
{
Answers.Add(answer);
}
return this;
}
}
答案始终为空。
最奇怪的是我总能保存第一次添加的答案。每隔一次我从repo拉测试并调用AddAnswer方法我在上面提到的地方得到null。调用repo.SaveChanges方法仅适用于第一次,数据插入数据库但在发生错误之后。 任何人都可以帮助我做错了吗?
我正在使用的存储库获取了我编写该问题的上述行所需的所有必要数据。
编辑1: 以下是我从repo获取数据的方法:
public interface IPSTRepository : IRepository<PTS>
{
}
这是IRepository接口:
public interface IRepository<TObject> where TObject : class
{
ICollection<TObject> GetAll();
Task<ICollection<TObject>> GetAllAsync();
TObject Get(int id);
Task<TObject> GetAsync(int id);
TObject Find(Expression<Func<TObject, bool>> match);
Task<TObject> FindAsync(Expression<Func<TObject, bool>> match);
ICollection<TObject> FindAll(Expression<Func<TObject, bool>> match);
Task<ICollection<TObject>> FindAllAsync(Expression<Func<TObject, bool>> match);
TObject Add(TObject t);
TObject Update(TObject updated, int key);
void Delete(TObject t);
int Count();
Task<int> CountAsync();
int SaveChanges();
Task<int> SaveChangesAsync();
}