简体   繁体   中英

Entity Framework Core, custom sql doesn't select expected value

I want to select a value depending on another table with a custom sql. The value is 1 if an entry in the other table exists and NULL if not. The sql works in SQL Server Management Studio perfectly fine. But when I run it in my application I get always NULL.

Here is the code of my model:

[Table("Projects")]
 public class ProjectsModel
 {
        [Required(ErrorMessage = "Angabe der ID ist erforderlich.")]
        [Display(Name = "Lfd")]
        [Key]
        public int Id { get; set; }

        [Required(ErrorMessage = "Name ist erforderlich.")]
        [Display(Name = "Name")]
        public string Name { get; set; }

        [NotMapped]
        public bool? userAtProject { get; set; }
}

And here is my custom sql:

  var Projects = _context.Projects.FromSql("
        SELECT p.Id, p.Name, (
        SELECT 1 AS Expr1 FROM TableAB WHERE (aId = a.Id) 
        AND (UserId = '" + Id + "')) AS userAtProject 
        FROM Projects AS p INNER JOIN TableA AS a ON p.Name = a.Name")
        .ToList();

The value of userAtProject is always NULL. I hope someone can help me what I'm doing wrong here.

If I'm right the [NotMapped] attribute says EF to not try to map/fetch that properties from database

Edit : Maybe try

[ReadOnly(true)]

instead?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM