문제

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

도움이 되었습니까?

해결책

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;}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top