简体   繁体   中英

LINQ to SQL: Insert into Primary and Foreign table

I'm trying to insert data into a primary table and a dependent table at the same time. A database relationship does exist between the two tables, and table Employee have an Identity column as the Primary Key.

I'm trying:

        Database.Employee emp = new Database.Employee()
        {
            x = DateTime.Now,
            y = "xxx"
        };
        Database.Skill skill = new Database.Skill()
        {
            Skill = "Reading"
        };
        emp.Skills = skill;  //Error on this line
        dc.Employees.InsertOnSubmit(emp);
        dc.SubmitChanges();

But I get the error that:

Cannot implicitly convert type 'Database.Skill' to 'System.Data.Linq.EntitySet'

It looks like Database.Employee.Skills is a collection, not a single object. Ie in the model it would look something like:

public class Employee
{
     ...
     public EntitySet<Skill> Skills { get; set; } // collection of skills
}

Your line of code

emp.Skills = skill;

is trying to instantiate a collection as a single instance, so you are getting conversion error.

As such the correct way to add a skill would be something like

emp.Skills.Add(skill);

Exact implementation depends on what Database.Employee.Skills is.

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