Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - Make Category field not required

I have two POCO objects:

public class Product
{
    public int ProductID { get; set; }
    public string Name { get; set; }
    public int CategoryID { get; set; }
    public virtual Category Category { get; set; }
}

public class Category
{
    public int CategoryID { get; set; }
    public string Name { get; set; }
}

So obviously, when I create a Product, I can select a category for that product. Or rather, a category is required.

I can't create a product without explicitly selecting a category, and my data is structured in such a way, that I don't want to create a "No Category" category entry.

I've thought about doing a many-to-many mapping between these two tables... but would like to avoid it if possible.

Either I'm doing something silly, or there really is no way to do this.

Any help would be appreciated!

like image 224
Tiny Avatar asked Jun 04 '26 22:06

Tiny


1 Answers

Make the CategoryID nullable. If you do not supply value for CategoryID it will be set to NULL in database.

public class Product
{
    public int ProductID { get; set; }
    public string Name { get; set; }
    public int? CategoryID { get; set; }
    public virtual Category Category { get; set; }
}
like image 133
Eranga Avatar answered Jun 08 '26 00:06

Eranga