MissioDei
MissioDei

Reputation: 809

Entity Navigation Property Question

I have a vendor model, I have a news item model. Can I make my vendor model optional inside of my news item model?

In other words...the news model is a class that will be turned into a view inside of my mvc project. This view will become a form that will create a news item. We want the option to associate a vendor with a particular news item (The news item is about the vendor, select the vendor from a drop down list), but we want this to be optional.

If I set Vendor as a navigation property of News item, doesn't that mean that a vendor is required? How would I accomplish this?

Thanks for any tips.

Upvotes: 0

Views: 504

Answers (2)

Slauma
Slauma

Reputation: 177133

In EF 4.1 in a class like this ...

public class News
{
    public int NewsId { get; set; }
    public Vendor Vendor { get; set; }
}

... Vendor would be an optional navigation property (Vendor = null is allowed). EF would assume a nullable foreign key column in the database.

If you want to expose a foreign key in the model you have to make sure that the FK property is nullable to have an optional relationship:

public class News
{
    public int NewsId { get; set; }
    public int? VendorId { get; set; }
    public Vendor Vendor { get; set; }
}

With a non-nullable foreign key property (public int VendorId { get; set; }) EF would assume a required navigation property.

In addition to these default settings you can also customize the relationship with data annotations or in Fluent API.

When you are working in the Model designer in Visual Studio there is the option to set the multiplicity of an end of a relationship to 0...1 or 1 representing an optional or a required property respectively.

Upvotes: 1

agradl
agradl

Reputation: 3536

Your relationship will have to be nullable and you can setup this relationship in the OnModelCreating event within your DbContext class. Here's a similar questions.

EF Code First - 1-to-1 Optional Relationship

Upvotes: 1

Related Questions