How to implement an ID field on a POCO representing an Identity field in SQL Server?

Posted by Dr. Zim on Stack Overflow See other posts from Stack Overflow or by Dr. Zim
Published on 2010-06-01T02:20:29Z Indexed on 2010/06/01 5:23 UTC
Read the original article Hit count: 229

Filed under:
|
|
|

If I have a Domain Model that has an ID that maps to a SQL Server identity column, what does the POCO look like that contains that field?

Candidate 1: Allows anyone to set and get the ID. I don't think we want anyone setting the ID except the Repository, from the SQL table.

public class Thing {
    public int ID {get;set;}
}

Candidate 2: Allows someone to set the ID upon creation, but we won't know the ID until after we create the object (factory creates a blank Thing object where ID = 0 until we persist it). How would we set the ID after persisting?

public class Thing {
    public Thing () : This (ID: 0) {}
    public Thing (int ID) {
        this.ID = ID
    }
    private int _ID;
    public int ID {
        get { return this.ID;};
    }

Candidate 3: Methods to set ID?

Somehow we would need to allow the Repository to set the ID without allowing the consumer to change it. Any ideas? Is this barking up the wrong tree? Do we send the object to the Repository, save it, throw it away, then create a new object from the loaded version and return that as a new object?

© Stack Overflow or respective owner

Related posts about c#

Related posts about repository