.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Inserting Foreign Key Value if it doesn't exist?

Posted By:      Posted Date: September 02, 2010    Points: 0   Category :ASP.Net
I am inserting a record and want to set the value for a foreign key but I am getting an error - I initally thought that it would insert it if it didn't exist but I must be wrong and want to confirm that I need to check all values and make a record for them if they don't exist... here's what I am trying to do - does his make sense?var newAllPart = new Part();                newAllPart.PartNumber = partNumber;                newAllPart.Manufacturer.ManufacturerName = partManufacturer; // error here if the Manufacturer doesn't exists already                newAllPart.PartType.PartTypeName = partType;                newAllPart.Category.CategoryName = partCategory;                newAllPart.DateCreated = DateTime.Now;                newAllPart.UserCreated = userCreated;                newAllPart.Package.PackageName = partPackage;    

View Complete Post

More Related Resource Links

SQL Server doesn't exist or access denied while connecting with Access 2010 ODBC

Hello all. I am using Access 2010 and SQL Server 2008 (locally). I can easily connect to server using SSMS and it works excellent. But when I want to import a table to Access 2010 using ODBC, it says that "SQL Server doesn't exist or access denied". It worked previously - almost 3 days ago, but now, it doesn't! Please help! Thanks Mohammad Javahery

core results web part - Property doesn't exist or is used in a manner inconsistent with schema sett

I edited the Fetched Properties section of my core results web part and added a mapped column <Column Name="owstaxIdKeyword"/> When I reload my page, I get this error: Property doesn't exist or is used in a manner inconsistent with schema settings.

Inserting null value into foreign key table with allow null enabled


Hey guys, 

I have 2 table Table A, Table B.

Table A - Parent Table

ID - Uniqueidentifier not null(PK)

Table B -Child Table              

ID - uniqueidentifier null(FK, TableA)

I have a stored procedure to insert data into Table B, but when I tried to insert a null value into column ID of table B, this error came up:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tableB_tableA". The conflict occurred in database "database name", table "table A", column 'ID'.

The statement has been terminated.

The insert statement in asp.net is like so:

sqlcommand.parameter.add(New Sqlparameter("ID", Nothing))

I am guessing adding nothing to the null value column is the problem, but i don't know how to fix it... can any1 help me?


The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tableB_tableA". The co

Inserting foreign key value using subquery




I'm playing around with a training-wheel database.  I have a table that stores magazine subscription info.  I have a lookup table that stores the delivery period, ie. 'weekly', 'monthly', etc.  I have a primary key ID field in tblPeriods and a foreign key field in the main table, tblMags.  I want to insert data into tblMags without having to memorize the correlation between the period key and the period itself.  Here's what I tried first:


 ( vcName,
  fkPeriodID )
 ( 'The New Yorker',
  (SELECT  tblPeriods_ID FROM tblPeriods
   WHERE vcPeriod = 'Weekly'));


This gives the following message:


Server: Msg 1046, Level 15, State 1, Line 6
Subqueries are not allowed in this context. Only scalar expressions are allowed.


I'm thinking there must be a way to insert data like this and take advantage of a foreign key relationship without looking up a value each time.  Any ideas?






Error : List doesn not exist


Hello Everybody , 

i have the following error every time i try to upload or add a document in my document Center site and i would like to fix it ; 

i am running a sharepoint 2010 installed on a windows 2008 connected to sql server 2008 ; and i am logon uing the admin account;

Error :

List does not exist.

The page you selected contains a list that does not exist.  It may have been deleted by another user.


Troubleshoot issues with Microsoft SharePoint Foundation.

Correlation ID: 4b2b6b11-e973-4bf1-9369-2fea6134e8de

Date and Time: 10/6/2010 11:21:25 AM


any help would be appreciated


Thank you




returning a date with a count of zero if it doesn't exist in the date range?


i have the following query.

SELECT DATEADD(dd,0, DATEDIFF(dd,0,accesseddate)) AS hitdate, COUNT(hitid) AS hitsperday
FROM hits h
ON h.urlid = u.urlid
WHERE (accesseddate BETWEEN DATEADD(d, -6, GETDATE()) AND GETDATE() AND u.userid = @userid)
GROUP BY DATEADD(dd,0, DATEDIFF(dd,0,accesseddate))

but if there were no "hits" for a particular date range in the last week i only get the dates returned where there were hits. i need to get all the days returned and where there were no results, i need a zero returned.

hitdate            hitsperday

2010-10-07     2
2010-10-06     58
2010-10-04     1645
2010-10-03     1192 

what i need to return is this:     

hitdate                 hitsperday

2010-10-08     0
2010-10-07     2
2010-10-06     58
2010-10-05     0
2010-10-04     1645
2010-10-03     1192

any suggestions?

thank you very much.

How to check for exist word before inserting?


This is what I have at the moment.

insLusHmoobDataContext lusHmoobDC = new insLusHmoobDataContext();

lusHmoob lhbLusHmoob = new lusHmoob();

lhbLusHmoob.wordID = Guid.NewGuid();
lhbLusHmoob.word = txtWord.Text;
lhbLusHmoob.usage = txtUsage.Text;
lhbLusHmoob.hmgTrans = txtEnglishTrans.Text;
lhbLusHmoob.engTrans = txtEnglishTrans.Text;
lhbLusHmoob.originate = txtOriginate.Text;
lhbLusHmoob.modDate = Convert.ToDateTime(DateTime.Now.ToLongDateString());
lhbLusHmoob.insertDate = Convert.ToDateTime(DateTime.Now.ToLongDateString());

Is there a way to check if the word already exist in the database before the insert is commited? Can I somehow incoporated into this Insert or do I have to do my verification separately?

Content Type 0x0101 doesn't exist while turning on the PublishingResources feature


I am trying to turn on the PublishingResources feature on SharePoint 2010 and I am getting following exception (copied from the log):

10/28/2010 12:28:56.55 w3wp.exe (0x0FE4)                       0x1234 SharePoint Foundation         General                       8wok Monitorable SPException thrown: Message: Nadrazený typ obsahu urcený identifikátorem typu obsahu 0x0101 neexistuje.. Stack:    at Microsoft.SharePoint.Utilities.SPUtility.ThrowSPExceptionWithTraceTag(UInt32 tagId, ULSCat traceCategory, String resourceId, Object[] resourceArgs)     at Microsoft.SharePoint.SPContentType..ctor(SPContentTypeId contentTypeId, SPContentType parentContentType, SPContentTypeCollection cts)     at Microsoft.SharePoint.SPContentType..ctor(SPContentTypeId contentTypeId, SPContentTypeCollection contentTypes, String name)     at Microsoft.SharePoint.SPContentTypeElement.ElementActivated(SPFeaturePropertyCollection props, SPSqlComma

Inserting InvoiceID "Key" field from Grid into Payment ListDetails "Foreign Key" field


Setup: A Grid called InvoiceGrid

            A ListDetails called DetailsView1 (for editing existing payments for the selected invoice)

            A ListDetails called DetailsView2 (in DetailsView1's EmptyDataTemplate for inserting new payments for the selected invoice) 

            A foreign Key restraint setup between the two tables



1) When I select an invoice that does not have a payment associated with it, the DetailsView2 displays as it should,  how do I auto-populate the DetailsView2 "InvoiceID" field with the InvoiceID field selected in the InvoiceGrid ?

2) How do I make the InvoiceID field in DetailsView2 "ReadOnly" so the user cannot accidentaly change it.

3) Is there any kind of Insert conformation that I can display if the payment is successfully inserted ?





delete from one table if a combination of data doesn't exist in another


this will work, but i am 100% certain there's a more efficient way:

create table stgClients(intClientId int, status1 varchar(50), status2 varchar(50), status3 varchar(50))

create table lkpClientStatus(intStatusId int, vchStatusCode varchar(50), bitDeleted bit)

create table trefClientsStatus(intClientId, intStatusId)

DELETE FROM trefClientsStatus WHERE cast(intClientId as varchar(10)) + '|' + CAST(intStatusId as varchar(10)) NOT IN
SELECT cast(a.intClientId as varchar(10)) + '|' + CAST(a.intStatusId as varchar(10)) FROM
(SELECT DISTINCT sc1.intClientId, cs1.intStatusId
FROM stgClients sc1 INNER JOIN lkpClientStatuses cs1 ON (LTRIM(RTRIM(sc1.status1)) = cs1.vchStatusCode AND cs1.bitDeleted = 0)
WHERE NULLIF(LTRIM(RTRIM(sc1.status1)), '') is not null
SELECT DISTINCT sc2.intClientId, cs2.intStatusId
FROM stgClients sc2 INNER JOIN lkpClientStatuses cs2 ON (LTRIM(RTRIM(sc2.status2)) = cs2.vchStatusCode AND cs2.bitDeleted = 0)
WHERE NULLIF(LTRIM(RTRIM(sc2.status2)), '') is not null
SELECT DISTINCT sc3.intClientId, cs3.intStatusId
FROM stgClients sc3 INNER JOIN lkpClientStatuses cs3 ON (LTRIM(RTRIM(sc3.status3)) = cs3.vchStatusCode AND cs3.bitDeleted = 0)
WHERE NULLIF(LTRIM(RTRIM(sc3.status3)), '') is not null) a

yes the trims and nullifs are

Updating a table - or add when the record doesn't exist



I'd like to be able to update a table from a VB application without the table being part of the project.

I know how to insert a record:


Dim connectionstring As String = My.Settings.AdminCentreConnectionString

Dim eSQL As String =

Editing a view which doesn't seem to exist


I've adjusted the default view of a document library to show 100 items at a time and received complaints that it's still only showing 15 items at a time.  Confused I had a user show me the exact steps he was taking to reproduce the issue and discovered that he's interacting with the library through its shortcut on the homepage of the site; in other words instead of clicking and opening the document library from the quick launch (or direct link) he's clicking through folders which are appearing on the web part of the home page.  You can tell he's not really in the document library based on the lack of "Document" and "Library" options in the ribbon. 

What's this view called?  Can I edit this view?  Or do I need to educate users not to use the shortcut from the webpart and to access documents through the library directly?

Thanks in advance.


_vti_bin\ReportBuilder doesn't exist? SP2010


HI every one

I am really struggling. I have gone through all the motions of setting up SSRS (Sharepoint 2010, SQL 2008 R2), and now when I am in my Report Library and I click "report builder report" it takes me through to my reporting server web url and all I see if a directory listing. So I did my investigation and found that I should have a directory under IIS called _vti_bin\ReportBuilder, and all i have is ReportServer - which is why I think my report builder app is not even bothering to open.


Any ideas on how to get that folder in there? I have spent about 9 hours on google and twitter and such, and nothing :\


Any help is greatly appreciated

If a date is null or doesn't exist return another date



I have 2 dates which are calculated members:

SELECT ReportingMonday ON 0
FROM DataCube

SELECT [FirstCubeDate] ON 0
FROM DataCube

ReportingMonday= StrToSet("[Dim Date].[Date Key].&[" + IIF(WEEKDAY(NOW())<=2,FORMAT(DATEADD("W",-5-Weekday(NOW()),CDATE(Now())),"yyyyMMdd"),FORMAT(DATEADD("W",2-Weekday(NOW()),CDATE(Now())),"yyyyMMdd")) + "]")

FirstCubeDate = HEAD([Dim Date].[Date Key].[Date Key].Members,1)

What I want is a named set to say:

if ReportingMondayis null or blank (so there isn't a report monday e.g. the data started on Tuesday) then return FirstCubeDate

Any Ideas?




Inserting new row in GridView in ASP.NET 2.0

The GridView was not designed to insert new rows, but there is a way to accomplish this with very little code. This article shows how to do that. The GridView was not designed to insert new rows, but there is a way to accomplish this with very little code.

Inserting personal error message in ValidationSummary



I am creating a web form that requires a lot of validation. I use many of the validation control in asp.net already like RequiredFieldValidator and CompareValidator. 

My Problem: after my custom validation for the value entered return an error message, and I pressed enter key when the field is empty, my custom error message is overlapped by my ValidationSummary. 

Setting my custom error to visible = false on button click also does not seem to work as it requires for me to enter the value first.

This made me think, is there a way to insert my custom validation inside the ValidationSummary as an error message like for other validation control?

Thanks in advance

Beginner: this doesn't make sense to me


Do you need and "empty" script tag in the head to run scripts that are in the body?  Also, can you run JQuery scripts if they're in the <head> tag?  The first sample only works if the JQuery script is in the form (and body) tag, not in the head - even if I add $(document).ready(function() { });

This works

<head runat="server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" />
<script type="text/javascript">
<form id="form1" runat="server">
<a href="">Here is a link</a>
<script type="text/javascript">
$('a').click(function () {
alert("you clicked me!");


This doesn't work.  Notice I removed the second <script> tag from the head

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="serve
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend