当页面加载Session()时插入

时间:2015-11-13 15:50:56

标签: c# .net sql-server

当页面打开时,我想在此页面中插入3个值,这是此格式之前的流派,艺术家,唱片公司的主键,并且将是外键,进入此表,即专辑。

我的桌子是

相册-------------

AlbumID主键

RELEASEDATE

RecordCompanyID外键

ArtistID外键

GenreID外键

RecordCompanies ------------------------------

RecodCompanyID Priamry Key

RecordComapnyName

流派---------------------------

GenreID主键

类型

艺术家------------------------------------------

ArtistID主键

ARTISTNAME

namespace WebApplication6
{
    public partial class WebForm15 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["genreid"] != null && Session["artistid"] != null && Session["recordcompanyid"] != null)
            {
                Label7.Visible = true;
                Label7.Text = "Welcome : " + Session["genreid"] + "Welcome : " + Session["artistid"] + "Welcome : " + Session["recordcompanyid"];
            }
            else
            {
                Response.Redirect("~/BenEManagementGenre.aspx");
            }


            if (!IsPostBack)
            {






                String Artists = System.Configuration.ConfigurationManager.ConnectionStrings["FleetManagementConnectionString"].ConnectionString;
                System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(Artists);

                int artistid = Convert.ToInt32(Session["artistid"]);
                int genreid = Convert.ToInt32(Session["genreid"]);
                int recodcompanyid = Convert.ToInt32(Session["recodcompanyid"]);


                SqlCommand command = new SqlCommand(@"INSERT INTO [dbo].[Albums] (GenreID,ArtistID,RecordCompanyID)
               VALUES (@Genre, @Artist,@RecordCompany);" + "select scope_Identity() as ID", con);



                command.Parameters.AddWithValue("@Genre", artistid);
                command.Parameters.AddWithValue("@Artist", genreid);
                command.Parameters.AddWithValue("@RecordCompany", recodcompanyid);

                con.Open();
                SqlDataReader rd = command.ExecuteReader();
                int ID = -1;


                while (rd.Read())
                {
                    ID = int.Parse(rd["ID"].ToString());

                }
                rd.Close();
                con.Close();

                Session.Add("albumid", ID);

            }

错误说

  

INSERT语句与FOREIGN KEY约束冲突   “fk_AlbumsRecordCompanyID”。冲突发生在数据库中   “KazuTest”,表“dbo.RecordCompanies”,列“RecordCompanyID”。

在我的理论中,当我打开页面时,我插入了3个外键值,所以我已经插入了外键。那么为什么会出现这个错误?

1 个答案:

答案 0 :(得分:2)

看看你如何添加参数:

command.Parameters.AddWithValue("@Genre", artistid);
command.Parameters.AddWithValue("@Artist", genreid);
command.Parameters.AddWithValue("@RecordCompany", recodcompanyid);

您将ArtistId放在GenreID列中,GenreId放在ArtistID列中。通过这种方式,不考虑外键的约束。

正确的版本应该是:

command.Parameters.AddWithValue("@Genre", genreid);
command.Parameters.AddWithValue("@Artist", artistid);
command.Parameters.AddWithValue("@RecordCompany", recodcompanyid);