简体   繁体   中英

Lookup data with EF6

Hello i'd like to create relation between EF Poco and DTO. Here is my situation I've got these 2 entities in my application

public partial class RFID_TAG
{
    public int TAG_ID { get; set; }
    public string RFID { get; set; }
    public Nullable<int> EMPLOYEE_ID{ get; set; }

    public virtual EMPLOYEE EMPLOYEE{ get; set; }
}

public partial class EMPLOYEE 
{
    public int EMPLOYEE_ID{ get; set; }
    public string FIRST_NAME{ get; set; }
    public string LAST_NAME{ get; set; }
    //ETC...
}

I also have this DTO

public class EMPLOYEELookUpData 
{
    public int EMPLOYEE_ID{ get; set; }
    public string FULL_NAME{ get; set; }
}

I'm using this DTO for specific selects where i only need EMPLOYEE's id and name, I've got CRUD view where user can add new tags it contains datagrid with that contains all tags and textbox thats bound to currently selected tags RFID and combobox which has SelectedItem bound to currently selected tags EMPLOYEE property. This is how i'm selecting data:

    private async void GetData()
    {
        Data = await DbContext.RFID_TAG.Include(x => x.EMPLOYEE).ToListAsync();
        EmployeesList = await DbContext.MPLOYEE.Where(x => x.ACTIVE == 1)
                                        .Select(x => new EMPLOYEELookUpData{EMPLOYEE_ID = x.EMPLOYEE_ID, FULL_NAME= x.FIRST_NAME + " " + x.LAST_NAME})
                                            .ToListAsync();
    }

But i can't figure how to make relation between EMPLOYEE and EMPLOYEELookUpData so that EF knows how to convert EMPLOYEELookUpData to EMPLOYEE.

I believe you can use AutoMapper for this: https://www.nuget.org/packages/AutoMapper/ . It can be installed using Nuget.

The code would look something like this:

using (MyEntities myEntities = new MyEntities())
            {
                List<EMPLOYEELookUpData> employeeLookupData;
                try
                {
                    employeeLookupData = myDB
                        .Employee
                        .Select(EMPLOYEELookUpData)
                        .Where(c => x => x.ACTIVE == 1)
                        .ToList();
                }
                catch (InvalidOperationException e)
                {
                    //Write a log entry
                }

I have not tested the code. You would have to create the mappings and create special mappings for : EMPLOYEELookUpData .FullName as it equals EMPLOYEE.FirstName + EMPLOYEE.Surname. You can find out how to do this by reading the documentation or posting another question on here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM