实体框架代码优先保存多次到一次

时间:2011-09-16 22:14:32

标签: entity-framework entity-framework-4.1

我在实体框架代码第一个应用程序的第3个导航属性上提交数据时遇到问题。

我的模型是这样的:(假设有一个名为User and Company的模型)

public enum UserCompanyRoleType
{
    Administrator,
    Creator,
    Follower
}
/// <summary>
/// User that belongs to a company
/// </summary>
public class UserCompany
{

    public int UserCompanyId { get; set; }

    public virtual User User { get; set; }
    public virtual int UserId { get; set; }

    public virtual Company Company { get; set; }
    public virtual int CompanyId { get; set; }

    public virtual IEnumerable<UserCompanyRole> Roles { get; set; }
}

public class UserCompanyRole
{

    public virtual int UserCompanyRoleId { get; set; }
    public UserCompanyRoleType RoleType { get; set; }

    public virtual UserCompany UserCompany { get; set; }
    public virtual int UserCompanyId { get; set; }

}

这是服务代码:

var creator = new UserCompany { UserId = userId };
//add the user as both creator and admin
creator.Roles = new List<UserCompanyRole> { new UserCompanyRole{RoleType = UserCompanyRoleType.Creator}}; //somehow this does not reach the database

company.Users = new List<UserCompany>();
company.Users.Add(creator);

db.Companies.Add(company);
db.SaveChanges();

这样可以保存公司和相关的用户公司,但不保存2个角色。如何在我评论的行中保存2个角色?

1 个答案:

答案 0 :(得分:1)

您需要将Roles属性设置为ICollection<UserCompany>类型。

public class UserCompany
{

    public int UserCompanyId { get; set; }

    public virtual User User { get; set; }
    public virtual int UserId { get; set; }

    public virtual Company Company { get; set; }
    public virtual int CompanyId { get; set; }

    public virtual ICollection<UserCompanyRole> Roles { get; set; }
}

EF 4.1不支持枚举,因此您将使用int字段来映射该属性。