asp.net-mvc - Entity Framework 6 - 如何将属性标记为非外键

标签 asp.net-mvc entity-framework

我将 ASP.NET MVC5 与 EF6 结合使用,并使用代码优先方法。

我在模型中有一个属性,我需要告诉 EF6 不是外键:

public class LogEntry
{
    public int ID { get; set; }
    public int LogDayID { get; set; }
    public int LogEntryTypeID { get; set; }
    public int DepartmentID { get; set; }
    public DateTime Clock { get; set; }
    public string Text { get; set; }

    public virtual LogDay LogDay { get; set; }
    public virtual LogEntryType LogEntryType { get; set; }
    public virtual Department Department { get; set; }
}

[NotMapped]
public class Department
{
    public int ID { get; set; }
    public string Title { get; set; }
}

模型部门有 [NotMapped],因为该模型不应存储在数据库中。

我认为这足以让 EF6 意识到 LogEntry 中的 DepartmentID 不应该是外键。但它却抛出一个错误,指出“部门”未映射。

编辑:即使我从 LogEntry 中删除 DepartmentID,它仍然会提示上述错误。

完整的错误信息如下:

"The type 'SupervisorLogWeb.Models.Department' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive or generic, and does not inherit from EntityObject."

最佳答案

显然,您的 ComplexType 被发现为实体 - 如果您决定将以前的实体重构为 ComplexType,就会发生这种情况。

ModelBuilder 将根据类型是否存在于 DbContext 中来决定它是否(或多或少)是实体。

因此请检查您的类是否仍在 Context 中定义为 DbSet 并进行相应调整。

关于asp.net-mvc - Entity Framework 6 - 如何将属性标记为非外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28026246/

相关文章:

javascript - 从 Mvc 模型渲染 div

javascript - ASP.NET MVC 项目中的客户端验证不验证规则

asp.net-mvc - 在哪里将日期转换为 UTC?

c# - EF 多重关系

entity-framework - TFS 中未包含 Entity Framework 5 POCO?

c# - 实时观察 WPF 中写入的 CSV

c# - 如何使用 Entity Framework 在现有的 SQL Server 数据库中创建一个表?

ASP.Net MVC与ASP.Net表单

c# - Linq to Entities Expression/Func 之间的性能差异

c# - 如何在 View 中引用隐式类型模型