简体   繁体   中英

Non-Nullable Virtual Propery in Entity Framework Code-First Model

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?

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; };
}

Add the RequiredAttribute to your porperty.

[Required]
public virtual Blog Blog { get; set; }

You should add this field to your Tag class:

[Required]
public Guid BlogId { get; set; }

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