Michael R
Michael R

Reputation: 75

bool true value to bit 1 from Entity to Sql through public Nullable<bool>

Got a weird problem I cant find a solution on. I got a row in my Guest table Which looks like this:

[GuestOnline] [bit] NULL,

So when I create a Guest I'm passing the value "true" from the client with a ajax call in json format to the WCF application that send the value to a property that looks like this for the moment.

[DataMember]
public Nullable<bool> GuestOnline
{
    get
    {
       return this.GuestOnline = true;
    }
    set
    {
        this.GuestOnline = true;
    }
}

The C# method that inserts the Guest to DB looks like this:

public Guest CreateGuest(Guest guest)
{
    context.Guests.Add(new Guest() { 
        GuestName = guest.GuestName, GuestOnline = true });
    context.SaveChanges();

    var result = context.Guests.First<Guest>(g => g.GuestName == guest.GuestName);

    return result;

}

This should clearly send the value "true" to my row in SQL. And the value should be converted to bit value = 1. But it doesn´t. I still get the value of NULL in my DB. The Ajax call looks like this:

function createguest() {
    if (userName.value !== "") {

        var guestData = '{"GuestName":"' + userName + '", "GuestOnline":"' + "true" + '"}';

        $.ajax({
            type: 'POST',
            url: 'http://localhost:35709/ChatService.svc/guests',
            contentType: 'application/json; charset=utf-8',
            data: guestData,
            dataType: 'json'

        });
    }

};

Any suggestions on what I'm doing wrong?

Upvotes: 0

Views: 1410

Answers (2)

JNYRanger
JNYRanger

Reputation: 7097

Assuming you are using LINQ to SQL / LINQ to Entities and the Guest object has already been mapped to your database try this. Lets also assume that Guests is the name of the entity created by the mappings that represents the table or structure containing Guest objects.

public Guest CreateGuest(Guest guest)
{
     guest.GuestOnline = true;
     context.Guests.InsertOnSubmit(guest);
     context.SubmitChanges(); //context.SaveChanges() for LINQ to Entity

     return guest;
}

This will use the Guest object passed to it directly and change the GuestOnline property to true. It will then insert a record of the object's properties into the Table (or other entity structure) named Guests Since there may be triggers to modify the record or other properties added when inserted (such as an auto-incrementing primary key value) the returned Guest object will contain all of the additional properties/column values. The only time you need to actually search the entity/table for a specific object is if you are updating it.

Upvotes: 1

AlexB
AlexB

Reputation: 7416

Don't use "true" but true (without " ")

Upvotes: 0

Related Questions