【问题标题】:Entity Framework Code First relationship save Issue实体框架代码优先关系保存问题
【发布时间】:2015-02-19 06:16:32
【问题描述】:

将新员工保存到数据库时遇到一些麻烦。

项目模型(删除无用字段):

public class Project{
        public virtual ICollection<EmployeeManager.Employee> Employees { get; set; }
    }

EmployeeManager.Employee 模型:

public class Employee{
        public virtual ApplicationUser User { get; set; }
        public virtual ProjectsManager.Project ProjectObj { get; set; }
    }  

功能:

public async Task AddNewEmployeeAsync(string projectId, string email, string fullname){       
        var projectInfo = await GetByIdAsync(projectId);
        var userInfo = new ApplicationUser();

        if (await _context.Users.AnyAsync(_ => _.Email == email)){
            userInfo = await _context.Users.FirstAsync(_ => _.Email == email);
        }
        else{
            ....
            userInfo = user;
        }

        projectInfo.Employees.Add(new EmployeeManager.Employee{
            User = userInfo
        });

        _context.Entry(projectInfo).State = EntityState.Modified;

        _context.SaveChanges();
    }

毕竟,我的数据库没有任何变化。

为什么?

如果我使用 _context.Employees.Add() -> 它会在数据库中创建新的项目实体。

【问题讨论】:

    标签: asp.net entity-framework entity-framework-6


    【解决方案1】:

    要使实体框架无需配置 (FluentApi) 即可创建正确的关系(一对多),您需要对 Employee 类进行一些更改

    public class Employee
    {
        public virtual ApplicationUser User { get; set; }
        public int ProjectId { get; set; } //foreign key maybe a string as defined in your Project class
        public virtual ProjectsManager.Project Project { get; set; }
    }  
    

    【讨论】:

    • 在这种情况下如何添加新员工? (对不起,愚蠢的问题)
    • 您可以根据您的问题添加新员工。只需将一个添加到您的员工项目集合中
    猜你喜欢
    • 1970-01-01
    • 2011-07-20
    • 2012-10-11
    • 2017-07-05
    • 2012-10-26
    • 2021-11-02
    • 2015-03-26
    • 2012-03-31
    • 1970-01-01
    相关资源
    最近更新 更多