using .net libs, how do I use an "Id" of type guid

using .net libs, how do I use an "Id" of type guid

nguyenm9nguyenm9 Posts: 20Questions: 3Answers: 0
edited March 2015 in Editor

mvc likes to use GUID as the pk type but when I do, I keep getting type errors. I can add a field as my pkey for Editor instantiation and define the type, but the code likes to insert another "Id" into the query so all my queries reference 2 "Id".

Also, does editor expect pk to be autoincremented on inserts?

// if I don't pass "Id" in to constructor, it will default to "id"
                var editor = new Editor(WebApiApplication.Db, "mytable", "Id")
                    .Model<MyModel>()
                    .Field(new Field("Id", typeof(Guid))  // need to set the type or casting error will occur
                    .SetValue(Guid.NewGuid())
                    )
                    .Field(new Field("Name").
                        Validator(Validation.NotEmpty()).
                        Validator(Validation.MaxLen(80))
                    )
                    .Field(new Field("Years")
                    )
                    .Field(new Field("Occupation")
                    )
                    .Field(new Field("Comments")
                    )
                    .Field(new Field("Ref_Url")
                        .Validator(Validation.Url())
                    );

thx, matt

edit: as a hack, i did in editor.cs

        private Dictionary<string, dynamic> _Insert()
        {
            // Insert the new row
            // need a guid for pk for insert
            _Field.Add(new Field(Pkey(), typeof(Guid)).SetValue(Guid.NewGuid()));

<snip>

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Hi,

    Sorry I didn't get a chance to look into this yesterday. I will try to do so today and report back! Good to hear you have a workaround for now :-)

    Regards,
    Allan

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    I've finally just looked at this, apologies again for the delay!

    A guid will work okay with Editor, but the value should be set as a default value for the primary key of the table. For example the following will work okay:

    CREATE TABLE test
    (
        id uniqueidentifier NOT NULL DEFAULT newid(),
        name varchar(255),
        title varchar(255),
        PRIMARY KEY (id)
    );
    

    It is important that the id must be a primary key, and that the default is set. That relates to your question about the pk being auto incremented - it doesn't need to be incremented as such, but the database should supply the value (be it a sequence, uuid or anything else).

    Regards,
    Allan

This discussion has been closed.