Search code examples
sql-serverasp.net-coredata-annotations

Best Approach to use [Column] or [ColumnAttribute] DataAnnotation in ASP.Net Core


I am new to asp.net core MVC framework(Before this I was using Laravel.)

I have a two table, Country and State, I will use InnerJoin to join those both table.

In my CountryModel, I have 4 property like below

public int CountryId { get; set; }

public string CountryName { get; set; }

public int StateId { get; set; }

public string StateList { get; set; }



SELECT c.CountryId,
       c.CountryName,
       s.StateId,
       s.States AS 'StateName'
       FROM _tbAddr_Country AS c
       INNER JOIN _tbAddr_State AS s on s.CountryId = c.CountryId

The above is my sql query, in my Country Model property I have no "StateName" property but I have "StateList", I just want to map "StateList" to "StateName" by using DataAnnotation just like below, I have tried

[ColumnAttribute("StateName")]
public string StateList { get; set; }

And

[Column("StateName")]
public string StateList { get; set; }

These two is not working for me, I know I can solve this problem by simply change the "StateList" to "StateName", But I hope I can find alternative way like use "Column" or "ColumnAttribute" Data Annotation to solve this problem. Any help is appreciated.

P/S: I using .net core 1.1 and SQL Server Management Studio 2014


Solution

  • That's not working the way you think.

    Column must match a table column name. You however have a projection using a join. So there is no table with such a name.

    EntityFramework Core 1.x and 2.0 doesn't support ad-hoc mapping from Views or queries to an arbitrary model. This feature is currently on roadmap for 2.1 as "Read-only view types in the model".

    Please note that this feature is located in the "stretch goal" section. It means, it's prioritized for 2.1, but changes are that not all of the goals will make it to 2.1 release and may be pushed to the next version if it's not done by the time 2.1 gets released (which should be around the time when ASP.NET Core 2.1 and/or .NET Core 2.1 releases)