2017-03-29 8 views
0

フォームのデータをdb内の2つのテーブルに挿入しようとしています。Raw SQL 'ASPに挿入' MVC

public ActionResult Cr([Bind(Include = "id,name,time")] appointment appointment, [Bind(Include = "pid,phone")] customer customer , string submit) 
     { 
     string str1 = "Insert Into appointment.id, appointment.name, appointment.time Values id,name,time" 
     string str2= "Insert Into customer.pid, customer.phone Values pid,phone" 
     var Query = dbb.Database.SqlQuery<ViewModel.custapp>(str1).ToList(); 
     var Query = dbb.Database.SqlQuery<ViewModel.custapp>(str2).ToList(); 
     return View("Index"); 
     } 

コードが間違っていてもデータがテーブルに挿入されていないかどうかはわかりません。

+1

代わりに挿入とビューモデルの両方に対してパラメータ化されたクエリを使用することをお勧めします。クエリは有効と思われますが、必要な値がおそらくアクションメソッドにバインドされていないため、データを挿入しません。 –

+0

構文は 'insert into ... values(...)'でなければなりません: – Jens

答えて

1

あなたが実際にあなたは、クエリ文字列が間違って書いて、テーブルにデータを挿入するための正しい構文は、テーブル名(カラム名)と値()

string str1 = "Insert Into appointment (id, name, time) Values (id,name,time)"; 
string str2= "Insert Into customer (pid, phone) Values (pid,phone)"; 
+0

あなたのコードと全く同じですが、カラムが見つからないようです。エラーは '無効な列名 'id'' –

+0

です。@ hudのIDは、テーブル – Usman

+0

のIDの列名と同じ名前である必要があります。列名は' id 'です。しかし、それでもエラー –

1

が必要になります。

INSERT INTO table_name (column 1, column 2, ...) VALUES (values) 

クエリ文字列は次のようになります。あなたを助け

string str1 = "Insert Into appointment (id, name, time) Values (id, name, time)"; 
string str2 = "Insert Into customer (pid, phone) Values (pid, phone)"; 

希望。

+0

あなたのコードとまったく同じように変更しましたが、列が見つからないようです。エラーは無効な列名 'id'です –

1

あなたがデータを挿入しているので、あなたのコードは、この

var sql = @"Insert Into appointment (name, time) Values (@name, @time)"; 
int noOfRowInserted = dbcontext.Database.ExecuteSqlCommand(sql, 
    new SqlParameter("@name", appointment.name), 
    new SqlParameter("@time", appointment.time)); 

ようにする必要があり、私はsql injectionSqlQuery<entity>にこのコマンドを防ぐためにパラメータを使用しますが、タイプentityのものであろういくつかのデータを返すが、あなたの中にいるときに使用されますデータを挿入している場合詳細についてはこちらを確認してください。 RAW SQL QUERY

関連する問題