Firkamon
Firkamon

Reputation: 807

Asp.Net - Unable to create a constant value of type. Only primitive types or enumeration types are supported in this context

There's a bunch of these here, but most of them involve a unique problem, and I haven't found one that applies to my code.

The error occurs when I attempt to convert to list with ToList().

fields contains no data when I look at the breakpoint, so it's probably the select command.

== and .Equals() yield the same result.

Controller code:

        var fields = from f in db2.Fields
                      where f.UpFile.Equals(upFile)
                      select f;
        ViewBag.Fields = fields.ToList();

Model code:

namespace steer.Models
{
    public class UpFile
    {
        [Key]
        [Display(Name="Auðkenni")]
        public int ID { get; set; }

        [Required]
        [Display(Name="Nafn")]
        public string Name { get; set; }

        [Required]
        [Display(Name = "Hlaðið þann")]
        public DateTime Date { get; set; }

        [Required]
        [Display(Name="Tegund")]
        public string FileType { get; set; }

        [Required]
        [Display(Name = "Stærð (kB)")]
        public int Size { get; set; }

        public string Columns { get; set; }

        public virtual ICollection<Field> Fields { get; set; }

        public class UpFileDBContext : DbContext
        {
            public DbSet<UpFile> UpFiles { get; set; }
        }
    }

    public class Field
    {
        public int ID { get; set; }
        public string values { get; set; }
        [ForeignKey("UpFile")]
        public int UpFileID { get; set; }
        public virtual UpFile UpFile { get; set; }

        public class FieldDBContext : DbContext
        {
            public DbSet<Field> Fields { get; set; }
        }
    }
}

Upvotes: 1

Views: 301

Answers (1)

gastonmancini
gastonmancini

Reputation: 1102

I suspect that the problem is that you are using a complex type in your query for comparison f.UpFile.Equals(upFile)

Why don't you try comparing by a primitive type such as the upFile id for example?

I would try:

 var fields = from f in db2.Fields
                      where f.UpFile.ID == upFile.ID
                      select f;
 ViewBag.Fields = fields.ToList();

Upvotes: 3

Related Questions