我想在不加载对象的情况下将对象添加到相关实体。 我的公司实体定义如下:
public class Company
{
public int ID { get; set; }
public List<Employee> EmployeeList{ get; set; }
}
像这样的员工实体
public class Employee
{
public int ID { get; set; }
public String Name{ get; set; }
}
我想将员工添加到该公司对象中的列表中,而不加载所有员工。
我知道我可以使用这个表达式
Company myCompany= systemBD.Companies.Include("EmployeeList").Find(1) myCompany.EmployeeList.Add(newEmployee)
但我担心这会耗费大量时间,因为我的数据库中有数千名员工。
有没有办法在不加载员工列表的情况下将新员工添加到现有公司? 我正在研究Attach方法,但它似乎不起作用。
using (var systemDB = new CompanyDB())
{
Employee employee = new Employee ();
Company companySearch = systemDB.Companies.Where(d => d.Name.Equals("John")).SingleOrDefault();
if (companySearch != null)
{
if (companySearch.EmployeeList != null)
{
systemDB.Companies.Attach(companySearch );
companySearch.EmployeeList.Add(employee);
systemDB.SaveChanges();
}
}
我尝试过该代码,但它无法正常工作。
答案 0 :(得分:3)
假设您已将公司和员工实体定义为具有从公司到其所有关联员工的集合的导航属性以及从员工到其单个关联公司的属性,则可以完成创建新员工和将其与Employees DB集中的现有公司关联。
[Table("Company")]
public partial class Company
{
public Company()
{
this.Employees = new HashSet<Employee>();
}
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
[Table("Employee")]
public partial class Employee
{
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
}
public partial class Database : DbContext
{
public Database()
: base("name=Database")
{
}
public virtual DbSet<Company> Companies { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Company>()
.Property(e => e.Name)
.IsUnicode(false);
modelBuilder.Entity<Company>()
.HasMany(e => e.Employees)
.WithRequired(e => e.Company)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Employee>()
.Property(e => e.Name)
.IsUnicode(false);
}
}
然后假设您已在系统中拥有ID为1的公司,您可以执行以下操作:
using (var database = new Database())
{
var company = database.Companies.Find(1);
if (company != null)
{
var employee = new Employee
{
Name = "John Doe",
Company = company
};
database.Employees.Add(employee);
database.SaveChanges();
}
}
或者......如果您确定公司ID 1肯定存在......
using (var database = new Database())
{
var employee = new Employee
{
Name = "John Doe",
CompanyId = 1
};
database.Employees.Add(employee);
database.SaveChanges();
}
答案 1 :(得分:-3)
我认为您需要更改数据库设计以完成您想要的任务。
Employee table
ID (Primary key)
Name
Company table
ID (Primary key)
Name
EmployeeCompany table
IDCompany (Foreign Key)
IDEmployee (ForeignKey)
这样你就可以完成你想要的事情