How do you allow for null foreign keys with CSLA

How do you allow for null foreign keys with CSLA

Old forum URL: forums.lhotka.net/forums/t/3578.aspx


SethSpearman posted on Saturday, September 22, 2007

Hello,

I am using GUIDs for my PK fields.

I have a meeting object.  This meeting object has an OPTIONAL LocationID which is a nullable foreign key.  The idea is that if a location is used it needs to be enforced to allow only values from the locatrions table.  But the field itself should be optional.  The location is optional when creating ameeting object. 

The locationID member is initialized to Guid.Empty.  This violates the constraint.  In my code how do I allow for this field to be nullable. 

So with that as background here are some specific questions:

1.  When creating the object. How do I set the location to null as follows
            set _meeting as meeting.newmeeting
            ....
            meeting.locationID=????  - what do I put here.

2.  How do I get it to assign a NULL value without doing an explicit set ofthe locationID. 

I could probably figure this out but want to do it the BEST way?

Thanks.

Seth

 

david.wendelken replied on Saturday, September 22, 2007

I assume you mean the FK in the database is being violated...

If so, before you send the Guid value to the database, check to see if it = Guid.Empty.
If it does, send System.DBNull.Value.

Or, if you are feeling more adventurous, clone the SmartDate class and turn it into a SmartGuid class.

Since I don't work with Guids much, I can't say which is the better approach... :)

phucphlq replied on Sunday, September 23, 2007

You should use Nullable<T>

Ex:

Nullable<Guid> Key;

If(Key.HasValue)

            DbParameter.Value = Key.Value;

Else

            DbParameter.Value = Dbnull.Value;

 

 


From: david.wendelken [mailto:cslanet@lhotka.net]
Sent: Sunday, September 23, 2007 04:15
To: phucphlq@dsp.com.vn
Subject: Re: [CSLA .NET] How do you allow for null foreign keys with CSLA

 

I assume you mean the FK in the database is being violated...

If so, before you send the Guid value to the database, check to see if it = Guid.Empty.
If it does, send System.DBNull.Value.

Or, if you are feeling more adventurous, clone the SmartDate class and turn it into a SmartGuid class.

Since I don't work with Guids much, I can't say which is the better approach... :)


SethSpearman replied on Wednesday, October 10, 2007

Both Phu and David,

Thanks for your help and answers.   Working great now.  I have created a bunch of shared NullIf... function which are doing the trick.

Thanks for the work and time you guys give to help newbies like me.

Seth

Copyright (c) Marimer LLC