Question

I'm using EF Code first.

I created two classes. For simplicity, imagine that I have a User table (class) and a FileAttachment table. I want to use the FileAttachment table with many other classes, so that any part of the application that requires having a FileAttachment can reuse that table. The problem is that when EF generates the schema, it creates a Foreign Key in the FileAttachment table back to User table. Is there a way to disable that?

Thanks

Était-ce utile?

La solution

You need to build an intermediate class.

public class UserDocument
{
    public int Id {get;set;}

    public int UserId {get;set;}
    public virtual User User {get;set;}

    public int FileAttachmentId {get;set;}
    public virtual FileAttachment FileAttachment {get;set;}
}

So your user class can now have:

public virtual ICollection<UserDocument> Documents {get;set;}

And in this case, FileAttachment class will not have reference to User.

If you want now to build some other document type, just implement another intermediate type, i.e. imagine you want to have CustomerDocument:

public class CustomerDocument
{
    public int Id {get;set;}

    public int CustomerId {get;set;}
    public virtual Customer Customer {get;set;}

    public int FileAttachmentId {get;set;}
    public virtual FileAttachment FileAttachment {get;set;}
}

And then your hypothetical Customer class would have:

public virtual ICollection<CustomerDocument> Documents {get;set;}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top