设置另一个没有关系的表的属性 实体框架



我正在尝试在我的实体中设置一个属性,该属性基于另一个实体,该实体彼此之间没有关系。该实体设置数据库中的属性,我希望从数据库中的另一个表设置其中一个属性,但我无法深入了解它。

例如

public class First {
    [Key]
    public int ProdId { get; set; }
    public string Supplier { get; set; }
    public virtual ICollection<Log> Logs { get; set; }
    [NotMapped]
    public bool IsSavedForLater
        {
            get
            {
                return Logs.Where(l =>
                {
                    var content = l.LogContent.JsonStringToObject<History>();
                    return (content.ProdId == ProdId && l.TableName == "Condition");
                }).Any();
            }
        }
}

如您所见,属性 IsSavedForLater 是[NotMapped],我希望从日志中设置此属性,

这是日志实体,

public class Log
{
    [Key]
    public int LogId { get; set; }
    public string LogContent { get; set; }
    public string TableName { get; set; }
    public DateTime LogDate { get; set; }
    public string BlameName { get; set; }
    public bool? Deleted { get; set; }
}

是否可以在没有任何数据库关系的情况下像这样导航?

伙计们,经过大量时间的弄清楚,我找到了我的解决方案。

所做的是,我首先在我的头等舱中添加了另一个属性,就像这样

public class First {
    [Key]
    public int ProdId { get; set; }
    public string Supplier { get; set; }
    public string TableName { get; set; }
    public virtual ICollection<Log> Logs { get; set; }
}

如您所见,First 类有一个新的属性TableName,它也在我的 Logs 类中,如下所示,

public class Log
{
    [Key]
    public int LogId { get; set; }
    public string LogContent { get; set; }
    public string TableName { get; set; }
    public DateTime LogDate { get; set; }
    public string BlameName { get; set; }
    public bool? Deleted { get; set; }
}

然后我在数据库上下文类中添加了一个模型生成器,如下所示,

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     modelBuilder.Entity<SmuForecasting>().HasKey(x => new { x.TableName }).HasMany(x => x.PsLogs).WithOptional().HasForeignKey(x => new { x.TableName });
}

这对我来说非常好,但有副作用,它取代了一开始设置的原始键,所以我最终做了一个完全不同的方法。

最新更新