0

我将一个实体与另一个实体联系起来:

[Table(Name = "Employees")]
public sealed class Employee
{
    [Column(Name = "Id", UpdateCheck = UpdateCheck.Never, IsPrimaryKey = true, IsDbGenerated = true, DbType = "Int NOT NULL IDENTITY")]
    public int Id { get; set; }

    [Column(Name = "Phone", UpdateCheck = UpdateCheck.Never, DbType = "Char(20)")]
    public string Phone { get; set; }

    [Column(Name = "UserId", UpdateCheck = UpdateCheck.Never, DbType = "Int NOT NULL")]
    public int UserId { get; set; }

    [Association(Storage = "_user", ThisKey = "UserId")]
    public User User
    {
        get { return _user.Entity; }
        set { _user.Entity = value; }
    }
    private EntityRef<User> _user;
}

[Table(Name = "Users")]
public sealed class User
{
    [Column(Name = "Id", UpdateCheck = UpdateCheck.Never, IsPrimaryKey = true, IsDbGenerated = true, DbType = "Int NOT NULL IDENTITY")]
    public int Id { get; set; }

    [Column(Name = "LastName", UpdateCheck = UpdateCheck.Never, DbType = "NVarChar(100)")]
    public string LastName { get; set; }

    [Column(Name = "FirstName", UpdateCheck = UpdateCheck.Never, DbType = "NVarChar(100)")]
    public string FirstName { get; set; }
}

然后我想创建一个员工:

var entity = new Employee
{
Phone = "Some",
User = new User
{
    FirstName = "Some", 
    LastName = "Some" 
}
};

context.GetTable<Employee>().InsertOnSubmit(entity);
context.SubmitChanges();

得到了这个:INSERT 语句与 FOREIGN KEY 约束“FK_Employees_Users”冲突

是否可以在 LINQ to SQL 中创建链接实体?

4

1 回答 1

0

尝试同时指定 的OtherKey属性AssociationAttribute。如果未指定,它将默认为相关类的键,但在您的情况下,不同类中键的名称不同(UserIdvs Id)。

[Association(Storage = "_user", ThisKey = "UserId", OtherKey="Id")]
public User User
{
    get { return _user.Entity; }
    set { _user.Entity = value; }
}
private EntityRef<User> _user;
于 2012-08-09T12:59:36.957 回答