简体   繁体   中英

Foreign key exception on INSERT with Linq-to-SQL but can't figure out why?

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_JobList_aspnet_Membership". The conflict occurred in database "C:\\JOBPOST\\APP_DATA\\ASPNETDB.MDF", table "dbo.aspnet_Membership", column 'UserId'.The statement has been terminated.

My FK_JobList_aspnet_Membership setup is:

  • Primary table ( aspnet_membership )
  • foreign key table ( JobList )
  • use column UserId(uniqueidentifier) for both tables, currently only set 2 UserId

JobList has its auto indexable primary key int JobId . No Action on Insert and update attribute, Delete set to Cascade

In the dbml, I also set UpdateCheck=UpdateCheck.Never for JobList Table

I don't understand why the exception happens, since I use membership service after user login. It should have no conflict. BTW, I am sure there is no other duplicate function for Inserting Item. Though throw exception, the new row data has been successfully inserted with correct userId. It keeps throwing this kind of exception for each time Inserting Item.

protected void LinqDataSourceDetail_Inserting(object sender, LinqDataSourceInsertEventArgs e) 
{        
    if (Page.IsValid == true)     
    {               
        JobPostDataContext db = new JobPostDataContext();

        JobList newJob = new JobList();
        newJob.JobTitle = ((TextBox)DetailsView1.FindControl("TB_JobTitle")).Text;
        newJob.Summary = ((TextBox)DetailsView1.FindControl("TB_Summary")).Text;
        newJob.Detail = ((TextBox)DetailsView1.FindControl("TB_Detail")).Text;
        newJob.CompanyName = ((TextBox)DetailsView1.FindControl("TB_CompanyName")).Text;
        newJob.CompanyEmail = ((TextBox)DetailsView1.FindControl("TB_CompanyEmail")).Text;
        String date = ((TextBox)DetailsView1.FindControl("TB_PostDate")).Text;
        newJob.PostDate = (DateTime)Convert.ToDateTime(date);
        newJob.IsTop = false;
        newJob.UserId = (Guid)Membership.GetUser(User.Identity.Name).ProviderUserKey;

        db.JobLists.InsertOnSubmit(newJob); 
        db.SubmitChanges();          
     } 
}

It means that the guid returned by (Guid)Membership.GetUser(User.Identity.Name).ProviderUserKey doesn't appear in the aspnet_membership table.

This is probably because Membership.GetUser(User.Identity.Name) is not finding the current user. In turn this is probably because User.Identity.Name is not in the aspnet_membership table either.

Suggested resolution:

  • output User.Identity.Name. One way to do this is to throw new Exception(User.Identity.Name)
  • Check that the name appears in the membership table.

When you inevitably discover that it does not, you can continue your debugging from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM