Define foreign key for ICollection in Entity Framework model

c# ef-database-first entity-framework-6 model reference

Question

How to define in Entity Framework 6, which columns will be used to reference data in an ICollection<>?

For example, we have a simple User-Information relation, were i can get all information from a user which updated or created the information:

public class User
{
    public int UserId
    {
        get;
        get;
    }

    // Here is the problem, how to define that EF
    // Has to use the CreateUser column
    public virtual ICollection<User> User_CreateUser
    {
        get;
        set;
    }   

    // Here is the problem, how to define that EF
    // Has to use the UpdateUser column
    public virtual ICollection<User> User_UpdateUser
    {
        get;
        set;
    }   
}

public class Information
{
    public int InfoId
    {
        get;
        set;            
    }   

    public int CreateUser
    {
        get;
        set;            
    }

    public int UpdateUser
    {
        get;
        set;            
    }

    [System.ComponentModel.DataAnnotations.Schema.ForeignKey("CreateUser")]
    public virtual User User_CreateUser
    {
        get;
        set;
    }

    [System.ComponentModel.DataAnnotations.Schema.ForeignKey("UpdateUser")]
    public virtual User User_UpdateUser
    {
        get;
        set;
    }       
}   

But i don't know, how to map this. For the simple foreign-keys it was easy over annotations.

I use database first but generating the models on my own. (Which works pretty good besides the ICollection<>.

Thank you!

1
0
7/6/2015 7:52:48 AM

Popular Answer

You've marked your second foreign key as User but it should be int.

public int UpdateUser { get; set; }

Try this:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

namespace Test
{
    public class User
    {
        public int UserId { get; set; }

        public virtual ICollection<User> User_CreateUser { get; set; }

        public virtual ICollection<User> User_UpdateUser { get; set; }
    }

    public class Information
    {
        public int InfoId { get; set; }

        public int CreateUser { get; set; }

        public int UpdateUser { get; set; }

        [ForeignKey("CreateUser")]
        public virtual User User_CreateUser { get; set; }

        [ForeignKey("UpdateUser")]
        public virtual User User_UpdateUser { get; set; }
    }
}
0
2/28/2017 7:43:44 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow