Search code examples
asp.net-mvcmaster-detailasp.net-mvc-viewmodel

To insert Data into Multiple Tables using MVC ASP.NET


I am new to MVC ASP.NET. Although this might have been solved in the past but I still can't get a complete Solution to my problem.

Problem : I have two tables
Video

Columns are : VideoID, FlimName, Description

VideoDetails

Columns are : VideoDetailsID , Actor , VideoID (foreign key from table video)

I am looking to insert data into both these tables from my MVC Model.[ first insertion into Video Table , followed by VideoDetails with the primary key of Video Table ie VideoID also getting inserted along with the record of VideoDetails Table ].

I have found some solutions to the problem , but it doesn't seem to merge into one complete solution.

Can I get some useful links on a step By step approach to this problem OR can someone help me with this solution.

I have read about the ViewModel approach on this forum but not clear still about its functionality and the flow. Please help.

Thanks,

Mangesh


Solution

  • The method you want is to use Entity Framework. You can find more information about Entity Framework here:

    http://www.asp.net/entity-framework

    If you are using Entity Framework, the code will look something like this:

    var context = new MyDBModelContext();
    
    tblVideo video = new tblVideo()
    {
        FileName = theFileName,
        Description = theDescription
    };
    
    context.tblVideos.Add(video);
    context.SaveChanges();
    
    tblVideoDetails details = new tblVideoDetails()
    {
        VideoID = video.VideoID,
        Actor = theActor,
    };
    
    context.tblVideoDetails.Add(details);
    context.SaveChanges();
    

    If you are using SQL, pass the respective details into your Stored Procedure and insert as follows:

    INSERT INTO Video
        (FileName, Description)
        VALUES(@FileName, @Description)
    
    INSERT INTO VideoDetails
        (VideoID, Actor)
        VALUES(SCOPE_IDENTITY( ), @Actor)
    

    NOTE: The above SQL should work, test first though.