Entity Framework class with list of object

asp.net-mvc c# entity-framework-6

Question

I'm using EF 6.0 and ASP.NET MVC with C# and I have two classes - project and feature:

public class project
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid id { get; set; }

    [Required]
    public string aliasName { get; set; }

    public virtual List<feature> features { get; set; }
}

and

public class feature
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int id { get; set; }

    [Required]
    public string name { get; set; }

    [DataType(DataType.MultilineText)]
    public string description { get; set; }
}

The end-user will pick more than one feature per project, and each project can contain different features.

How can I setup this in EF and store this selection in db?

In dbContext I have at this moment:

public DbSet<project> Projects { get; set; }
public DbSet<feature> Features { get; set; }
1
1
12/8/2016 9:43:39 PM

Popular Answer

Right now, you are trying to store the entire list of "Features" into the "Project" database when all you need to store is a unique identifier for each "Feature" which is the Feature.id property. So "Project" could be:

public class project
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid id { get; set; }

    [Required]
    public string aliasName { get; set; }

    [ForeignKey("Features")]
    public virtual List<int> featureIds { get; set; }
}

When you need specific Feature data, just query the Feature database for the specific feature id. Here is more information about using foreign keys within Entity.

3
12/8/2016 9:11:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow