Entity Framework Query Duplicate on Foreign Key

Saya mengalami kasus unik. Query yang dihasilkan DbContext error, padahal model auto generate ADO.NET.

Struktur database

database

Kelas project.js

[code language=”csharp”]public partial class project
{
    public int id { get; set; }
    public string name { get; set; }
    //public int contractor_id { get; set; }
    public string photo { get; set; }
    public string description { get; set; }
    public Nullable<System.DateTime> start_date { get; set; }
    public Nullable<System.DateTime> finish_date { get; set; }
    public Nullable<bool> is_featured { get; set; }
    public bool deleted { get; set; }
    public string project_stage { get; set; }

    public virtual contractor contractor { get; set; }
}
[/code]

Memanggil fungsi

[code language=”csharp”]
IQueryable<project> list = context.project;

//…

var takeList = list.Skip(skip).Take(take);
List<project> result = takeList.ToList();
[/code]

Menyebabkan error di query yang di-generate pada fungsi ToList().

SELECT TOP (10)
    [Extent1].[id] AS [id],
    [Extent1].[name] AS [name],
    [Extent1].[contractor_id] AS [contractor_id],
    [Extent1].[photo] AS [photo],
    [Extent1].[description] AS [description],
    [Extent1].[start_date] AS [start_date],
    [Extent1].[finish_date] AS [finish_date],
    [Extent1].[is_featured] AS [is_featured],
    [Extent1].[deleted] AS [deleted],
    [Extent1].[project_stage] AS [project_stage],
    [Extent1].[contractor_id1] AS [contractor_id1]
    FROM ( SELECT [Extent1].[id] AS [id], [Extent1].[name] AS [name], [Extent1].[contractor_id] AS [contractor_id], [Extent1].[photo] AS [photo], [Extent1].[description] AS [description], [Extent1].[start_date] AS [start_date], [Extent1].[finish_date] AS [finish_date], [Extent1].[is_featured] AS [is_featured], [Extent1].[deleted] AS [deleted], [Extent1].[project_stage] AS [project_stage], row_number() OVER (ORDER BY [Extent1].[id] DESC) AS [row_number]
        FROM [dbo].[project] AS [Extent1]
    )  AS [Extent1]
    WHERE [Extent1].[row_number] > 0
    ORDER BY [Extent1].[id] DESC

Dapat dilihat, ada tambahan contractor_id1, yang sebenarnya tidak terdapat di tabel & model. Solusi sementara menghapus atribut contractor_id di kelas Project.

Update (13 Mei)
Solusi lebih baik dengan menambahkan atribut ForeignKey
[code language=”csharp”]
[ForeignKey("contractor_id")]
public virtual contractor contractor { get; set; }
[/code]

Chandra Oemaryadi has written 244 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>