Arve Systad
Arve Systad

Reputation: 5479

Entity Framework returns null object when row has null values

I have an existing database (which I cannot modify in any way) that I'd like to use EF to code against. There are no primary keys, foreign keys or actual relationships between tables - everything seems to be handled by applications using the DB. For most of the tables/entities, this has been trivial. However, I've got one class, like the one below (simplified) that I'm struggeling with.

[Table("tableName")]
public class MyClass
{
    [Key]
    [Column("id")]
    public int? Id { get; set; }

    [Column("name")]
    public string CompanyName { get; set; }

    [Column("address")]
    public string Address { get; set; }
}

Things like _context.MyClasses.Where(x => x.Address == "something") work fine. However, it seems that when the id column is NULL in the DB, i get a null object back - even though CompanyName and Address have values. And I need those values, regardless of whether id (or whatever else) is null. Is there some way to force EF to generate the objects and ignore empty columns?

Removing or movin the [Key] attribute gives me an exception like "Must have a key column" (and the Id-column is also used to map a collection of other classes into this one if there are any that match).

UPDATE Don't think about the Id-column as an actual identifier. It's basically just an integer with a stupid name.

Upvotes: 3

Views: 6106

Answers (4)

Arve Systad
Arve Systad

Reputation: 5479

The solution

Like Andreas Niedermair commented on my question, I've now added [Key] to multiple columns in the database. I found that four columns together as a composite key is always unique in this case.

Since I'm never inserting new content to the database, this seems like a decent solution in this edge case scenario, I guess.

Upvotes: 1

Halo
Halo

Reputation: 1532

You need to have a Key column. EF requires you to have one. For your purposes, though, you can use an alternative way:

Set your Id's StoreGeneratedPattern property as Identity, and leave its generation and management to EF. Do not use Id for your nullable purposes; create another column like MyId, which is Nullable and not EntityKey, and use it any way you want.

Upvotes: 1

ChrisF
ChrisF

Reputation: 137108

You must have a Key column and that column must contain values for this to work. Marking a column as Key indicates that this is the Primary Key column for that table.

If the Key column contains a null value then that row won't be returned to the client. If the Id column isn't the primary key (as it can contain a null value) then you need to add a new column that can act as the primary key.

Upvotes: 2

Michal B.
Michal B.

Reputation: 5719

You cannot put a KeyAttribute above Id property if it is nullable in your database. That's what's causing you the problems...

The primary keys cannot be nullable, but I guess you know that...

Upvotes: 3

Related Questions