开发者

Entity Framework 4.1 Foreign Key question

I'm trudging ahead with an ecommerce database desgin in EF 4.1 Code First.

I've come to a situation where I think I'm justified, but not sure..

Consider:

class Download
{
    int ID
    string Mime
    string Filename
    string Extension
}

class DownloadBinary
{
    int ID
    int DownloadID
    Download Download
    byte[] Binary
}

class DownloadURL
{
    int ID
    int DownloadID
    Download Download
    string URL
}

Now I've placed the Foreign K开发者_开发技巧eys for Download in the other two classes as I wish to remove nulls basically. Also this has the byproduct of allowing multiple DownloadBinary and DownloadURL classes per Download class, which seems ok. But this seems the wrong way round from an EF point of view, as the Download class does not encapsulate the DownloadBinary and DownloadURL classes.

I know I can search the DbContext and retireve DownloadBinary and DownloadURL classes for a given Download class ID, so i can get data out ok.

If I held DownloadBinary ID and DownloadURL ID in the Download class, I could be subject to nulls, which is my point for doing it this way..

I'm really expecting to enforce a one to zero or one relationship from Download to DownloadBinary or DownloadURL classes in my data input forms..

I don't see much of a problem here, but what do more experienced people think??


Remove DownloadID from both DownloadBinary and DownloadUrl and map ID of these classes as foreign key to ID of Download. EF supports one-to-one relation only over primary keys because it doesn't support unique keys.

modelBuilder.Entity<Download>()
            .HasOptional(d => d.DownloadBinary)
            .WithRequired(db => db.Download);


modelBuilder.Entity<Download>()
            .HasOptional(d => d.DownloadUrl)
            .WithRequired(du => du.Download);

Both DownloadBinary and DownloadUrl must not use autogenerated Id in database because their ID is defined by Download: modelBuilder.Entity() .Property(db => db.ID) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

modelBuilder.Entity<DownoladUrl>()
            .Property(du => du.ID)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜