none
Create record. How should I do this? RRS feed

  • Question

  • Hello,

    I have the following SQL tables (I am posting only the needed columns):

    create table dbo.Users (
      Id int identity not null,
      Username nvarchar(100) not null
    ) -- Users

    create table dbo.Professors
    (
      Id int identity not null,
      UserId int not null,
      CurriculumVitae nvarchar(max) null
    ) -- Professors

    create table dbo.ProfessorsLevels
    (
      ProfessorId int not null,
      LevelId int not null,
        constraint PK_ProfessorsLevels primary key clustered(ProfessorId, LevelId)
    ) -- ProfessorsLevels

    I created a Linq to SQL model and got the following entities:
    User, ProfessorLevel and Level

    I need to insert a User, a Professor and its Levels and I have the following:

    public void Create(FormUser formUser)

          User _user = new User {  
            Username = formUser.Username
          };
          _context.Users.InsertOnSubmit(_user);

          Professor _professor = new Professor {
            UserId = _user.Id,
            CurriculumVitae = formUser.Professor.CurriculumVitae
          };
          _context.Professors.InsertOnSubmit(_professor);

          IList<ProfessorLevel> levels = formUser.Professor.Levels.Select(l => new Entities.ProfessorLevel { LevelId = l.Id, ProfessorId = ?????
          _context.ProfessorLevel.InsertAllOnSubmit(levels);

    1. When I create the Professor can I use: UserId = _user.Id.
        The Id's are identities and generated on the database ...

    2. How can I define the ProfessorId on each Level being created?

    Is this the way to this or should I do it in some other way?

    formUser is a model received from a web form that contains the values to be used to fill the entities.
    formUser as a similar structure than the Entities.

    Thank,
    Miguel
    Sunday, September 27, 2009 6:10 PM

Answers

  • Hi Miguel,

     

    For your first question, you can get the userid by calling submitchanges.

     

                User user = new User

                {

                    username = "edith"

                };

     

                context.Users.InsertOnSubmit(user);

                context.SubmitChanges();

                MessageBox.Show(user.id.ToString());

     

    For your second question, I think you need to insert into ProfessorLevel and Professor table manually. Since LINQ to SQL is not like EF, you’ll need to maintain the relationship by them manually.

     

     

    Best Regards

    Yichun Feng


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    • Marked as answer by Yichun_Feng Monday, October 5, 2009 1:49 AM
    Wednesday, September 30, 2009 7:38 AM