How to implement an identifier field in POCO representing an Identity field in SQL Server?

If I have a domain model that has an identifier that maps to the SQL Server authentication column, then what looks like POCO does this field contain?

Candidate 1: Allows you to set and get an identifier. I donโ€™t think we want someone to set the identifier, except the repository, from the SQL table.

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

Candidate 2: Allows someone to set an identifier at creation, but we will not know it until we create an object (factory creates an empty Thing object, where ID = 0, until we continue it). How did we set the identifier after saving?

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: ID setting methods?

- , . ? ? , , , ?

+3
2

, InvalidOperationException, ?

, , . ? , , . , /, , , ..

+4

, readonly, :

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

, _ID .

+2

Source: https://habr.com/ru/post/1747919/


All Articles