在尝试了各种各样的数据注释和fluentapi之后,我能想到的最干净的解决方案是非常简单的,这两种方法都不需要。它只需要将“private”构造函数添加到将“DbContext”对象注入的Conversation类(如果使用延迟加载,则添加“protected”构造函数)。只需将“Conversation”和“Message”类设置为一个普通的一对多关系,并且现在可以从“Conversation”实体中获得数据库上下文,就可以使用Find()方法使“LastMessage”简单地从数据库返回查询。Find()方法还使用缓存,因此如果多次调用getter,它只会访问数据库一次。
以下是有关此功能的文档:
https://docs.microsoft.com/en-us/ef/core/modeling/constructors#injecting-services
注意:“LastMessage”属性是只读的。要修改它,请设置“LastMessageID”属性。
class Conversation
{
public Conversation() { }
private MyDbContext Context { get; set; }
// make the following constructor 'protected' if you're using Lazy Loading
// if not, make it 'private'
protected Conversation(MyDbContext Context) { this.Context = Context; }
public int ID { get; set; }
public int LastMessageID { get; set; }
public Message LastMessage { get { return Context.Messages.Find(LastMessageID); } }
}
class Message
{
public int ID { get; set; }
public int ConversationID { get; set; }
public virtual Conversation Conversation { get; set; }
}