0

I have two tables to which I have to make insert to

Table 1 : Project

  • projectId
  • Name
  • Description

Table 2 : Access

  • id
  • userId
  • projectId

Now I am using ASP.NET MVC 4 with Entity Framework, now my question is how do I make insert to both this table ?

I mean I know I can make insert to Table 1 using EF, but then I need the projectId(which is generated with the first insert) to make the second insert.

I am not sure of how to go about it. Please some one guide me on this

2 Answers 2

3

When you save an object, the EF will populate the auto generated Key fields of the inserted objects:

public ActionResult Index() { 

    var ctx = new FooBarDbContext();

    var foo = new Foo();
    foo.Bar = "FooBar";
    ctx.Foos.Add(foo);
    ctx.SaveChanges();

    // now you have the Id for Foo object.

    var bar = new Bar();
    bar.FooId = foo.Id;
    ctx.Bars.Add(bar);
    ctx.SaveChanges();

    // do what you need now.
}
Sign up to request clarification or add additional context in comments.

Comments

2

public ActionResult Index()

{

ProjectContext db = new ProjectContext ();
var project = new Project();
var access = new Access();

project.Name = “Project Name”;
project.Description = “Project Description”;

access.UserId = 1; // Fill with your userId
access.Project = project;

db.Access.Add(access);
db.SaveChanges();// save project and access

}

// In Models folder

public class ProjectContext: DbContext

{

 public DbSet<Project> User { get; set; }
 public DbSet<Access> Contact { get; set; }

}

// Also in Access Class you must define Project

public class Access

{

[Key]
public int id{ get; set; }
public int UserId {get;set;}
[ForeignKey("Project")]
public int ProjectId { get; set; }

public virtual Project Project { get; set; }
// This line make relation between project and access

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.