Cameron Castillo
Cameron Castillo

Reputation: 2832

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'

Upvotes: 1

Views: 830

Answers (1)

user1666620
user1666620

Reputation: 4808

It looks like Database.Employee.Skills is a collection, not a single object. I.e. 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.

Upvotes: 1

Related Questions