Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

c# - NotMapped Field not get assigned by values on procedure calling in .NET Core

I have a model of type DbQuery in my context for executing a stored procedure in it.

public class DynamicClass
{
    public int ItemId { get; set; }
    [NotMapped]
    public string Title { get; set; }
    [NotMapped]
    public string TitleArabic { get; set; }
    public int? SeasonNumber { get; set; }
}

Query:

SELECT ItemId, Title, TitleArabic, SeasonNumber 
FROM dynamicclass
List<DynamicClass> Result = context.DynamicClass.FromSql("SELECT ItemId,Title,TitleArabic,SeasonNumber From dynamicclass").ToList();

The query is working fine but the NotMapped fields are not getting values while executing the query.

My query may or may not contain Title and TitleArabic and that is why I have assigned NotMapped annotation to these fields.

If I removed all the NotMapped annotations and query results doesn't contain all the columns I have specified in the model, then I get an error

The required column 'Title' was not present in the results of a 'FromSql' operation

How can I solve this or is there any better idea?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The NotMappedAttribute excludes mapping of the denoted properties by the database. This means the properties Title and TitleArabic will not get values if you read something from your database and only after you assign something manually. If the table you're reading the data from got Title and TitleArabic columns you can just remove the NotMapped Attribute to fill these values when reading from your table. Otherwise you can specify what these properties should return manually. For example:

public class DynamicClass
{
    public int ItemId { get; set; }
    [NotMapped]
    public string Title { get; set; }
    [NotMapped]
    public string TitleArabic => GetArabicTitle(Title);
    public int? SeasonNumber { get; set; }
}

If you execute a query which wouldn't return Title or ArabicTitle the properties on the resulting object would just be null without the NotMapped Attribute.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...