为什么此字段无效?

时间:2019-03-05 13:30:14

标签: c# asp.net-mvc entity-framework

当我想发送数据进行查看时,出现无效的列错误CreamType_Identer image description here

System.Data.Entity.Core.EntityCommandExecutionException: 'An error occurred while executing the command definition. See the inner exception for details.'

SqlException: Invalid column name 'CreamType_Id'.

我以身作则。但这是行不通的,我也不知道该如何解决

我的模特

public class CreamTypeModel
{
    [Key]
    public int Id { get; set; }
    public string Type { get; set; }
}

public class CreamModel
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
    public string ImageName { get; set; }

    public int? Type_id { get; set; }
    public CreamTypeModel CreamType { get; set; }
}

与示例中的public CreamTypeModel CreamType { get; set; }无关。

我在数据库中的代码

CREATE TABLE [dbo].[CreamTypeModels] (
[Id]   INT            IDENTITY (1, 1) NOT NULL,
[Type] NVARCHAR (100) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

CreamTypeModels

CREATE TABLE [dbo].[CreamModels] (
[Id]          INT             IDENTITY (1, 1) NOT NULL,
[Name]        NVARCHAR (70)   NOT NULL,
[Description] NVARCHAR (250)  NOT NULL,
[Price]       DECIMAL (18, 2) NOT NULL,
[ImageName]   NVARCHAR (100)  NOT NULL,
[Type_id]     INT             NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
FOREIGN KEY ([Type_id]) REFERENCES [dbo].[CreamTypeModels] ([Id]) ON DELETE SET NULL
);

CreamsModels

存储库代码

public class CreamRepository : ICreamRepository
{
    private CreamEFDbContext context = new CreamEFDbContext();

    public IEnumerable<CreamModel> CreamList
    {
        get { return context.CreamModels.Include(x => x.CreamType); }
    }

    public IEnumerable<CreamTypeModel> CreamTypeList
    {
        get { return context.CreamTypeModels; }
    }
}

和控制器方法

[HttpGet]
    [Authorize(Roles = "Administrator")]
    public PartialViewResult TableCreams()
    {
        return PartialView(creamManager.CreamList.ToList());
    }

我找到了解决方法,也将数据库中的字段public int? Type_id { get; set; }重命名为public int? CreamTypeModel_id { get; set; }。但是真的很有趣,为什么那不起作用?没有此修复程序?有人知道吗?

1 个答案:

答案 0 :(得分:0)

您如何进行实体框架配置?自从我使用它已有一段时间了,但我似乎记得您必须明确命名外键。

看看这个答案

https://stackoverflow.com/a/28001707/385965