0

I'm using AdventureWorks sample database in a project. I can display the Customer's (being various stores) information using vStorewithDemographics. It's a view retrieving different pieces of data from different tables in database.

I want my program to insert a new customer into the database using linq to entities and I'm not sure how to go about this. Inserting into the view just gives me errors, which I thought would happen because it's not a table.

Any way to go about this?

1 Answer 1

1

yes it is possible follow following steps

--> Create a instead of trigger and using it you can perform it Eg, I have two table customer and customerContacts latter contain the phone number of customer and a view name customer details will bring upon all the details of customer as below

create view [dbo].[CustomerDetails] as select c.*,cc.PhoneNumber from customer c inner join customerContact cc on c.CustomerId = cc.CustomerId

For inserting in have create a instead of trigger

Create TRIGGER trgInsteadOfUpdate ON dbo.CustomerDetails

INSTEAD OF INSERT

AS

Declare @Id int

-- Insert into Customer INSERT INTO customer SELECT CustomerName,CustomerAddress,State,Country FROM inserted

Set @Id = SCOPE_IDENTITY()

-- Insert into CustomerContact INSERT INTO customerContact SELECT PhoneNumber,@Id FROm inserted

GO

When for inserting in the linq i can user any of the following two ways

//Insert into view

var newCusContact = new CustomerDetail{ Country="India", CustomerAddress="bbb", CustomerName="Tested", PhoneNumber="7879654", State="Delhi" };

db.CustomerDetails.InsertOnSubmit(newCusContact);

db.SubmitChanges();

OR

string insertStatement = "insert into CustomerDetails(CustomerName,CustomerAddress,State,Country,PhoneNumber) values('DummyValue','DummyValue','Delhi','India','123459')";

db.ExecuteQuery(insertStatement);

db.SubmitChanges();

Hope this helps you

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.