2

I need to generate two database tables with a one-to-many relationship from my site's Entity Framework models; Blog and Tag. A blog can have many tags but a tag can only belong to one blog.

My Blog model consists of an ID property (Guid) as a primary key and a Name property (string). Similarity my Tag model consists of an ID property (int) as a primary key and a Name property (string). The Tag model also has a virtual property Blog which should generate a foreign key to the Blog table's ID column.

Below is an extract from my model classes:

public class Blog
{
    public Guid ID { get; set; }
    public string Name { get; set; }
}

public class Tag
{
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual Blog Blog { get; set; }
}

When the database is created using code-first, the Blog_ID column in the Tag table allows a null or a random GUID to be inserted. How do I enforce it to never allow nulls or a value other than an existing and valid Blog ID using a code-first approach?

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Jonny
  • 29
  • 3

3 Answers3

1

Your class should be declared similar to the below code.

using System.ComponentModel.DataAnnotations;
suing System.ComponentModel.DataAnnotations.Schema

public class Tag
{
    public int ID { get; set; }
    public string Name { get; set; }
    [Required]
    [ForeignKey("BlogId")]
    public virtual Blog Blog { get; set; }

    public virtual Guid BlogId { get; set; };
}
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
0

Add the RequiredAttribute to your porperty.

[Required]
public virtual Blog Blog { get; set; }
Fabian S.
  • 909
  • 6
  • 20
0

You should add this field to your Tag class:

[Required]
public Guid BlogId { get; set; }
Tjoep
  • 82
  • 4