Alexander Derck
Alexander Derck

Reputation: 14488

Is many to optional one relation possible?

I have the following situation: a Device can have multiple Subscriptions, but a Subscription has maximum one Device or none at all. In my database Subscriptions has a foreign key DeviceID which is Nullable (not the ID property in Device class). At the moment for some reason the following fluent code works:

            modelBuilder.Entity<Device>()
            .HasMany(e => e.Subscriptions)
            .WithRequired(e => e.Device)
            .WillCascadeOnDelete(false);

If I choose WithOptional(), which should be logical, I get errors. The error is this ModelvalidationError:

Additional information: One or more validation errors were detected during model generation:

Entities.Device_Subscriptions: : Multiplicity conflicts with the referential constraint in Role 'Device_Subscriptions_Source' in relationship 'Device_Subscriptions'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

However If I now query for example (with the .WithRequired(...) code)

db.Subscriptions.Where(s => s.DeviceID == null).Count();

I get zero, although there is one Subscription in my database with DeviceID null.

(partial)Model for Device:

public class Device
{
    public Device() : base()
    {
        Subscriptions = new HashSet<Subscription>();
    }
    [Key]
    public decimal DeviceID { get; set; }

    public virtual ICollection<Subscription> Subscriptions {get; set;}
}

(partial)Model for Subscription:

public partial class Subscription
{
    [Key]
    [Column(Order = 0)]
    public decimal? DeviceID { get; set; }

    [Key]
    [Column(Order = 1)]
    [StringLength(50)]
    public string Type { get; set; }

    public virtual Device {get; set;}
}

Upvotes: 2

Views: 145

Answers (1)

Vlad274
Vlad274

Reputation: 6844

The [Key] attribute is used to declare the Primary Key of an Entity. Having a nullable value as part of a PK doesn't really make sense.

From the comments, it seems that what you're really looking to accomplish is having an Index on (DeviceID, Type). In EF 6.1, they added the [Index] attribute which should accomplish this. Reference

Upvotes: 1

Related Questions