2

With EF 5.0.0, VS 2012 and .NET 4.5, when I add a new ADO.NET Entity Data Model from an existing SQL Server 2012 database, the generated code does not differentiate between a nullable and non-nullable varchar. For e.g. TTITLE is non-nullable but CITY is nullable in my database, but they end up like following in the generated code - which in turn creates validation issue. Shouldn't TITLE property be decorated by [Required] attribute by EF by default? It does generated differentiates accurately between nullable and non-nullable int.

public partial class AWARD
{
    public int ID { get; set; }
    public int PERSON_ID { get; set; }
    public string TITLE { get; set; }
    public string CITY { get; set; }
    public Nullable<int> STATE_PROVINCE { get; set; }
    public Nullable<int> COUNTRY { get; set; }
    public string ORGANIZATION { get; set; }
    public int YEAR { get; set; }
    public Nullable<int> MONTH { get; set; }

    public virtual PERSON PERSON { get; set; }
    public virtual V_COUNTRY V_COUNTRY { get; set; }
    public virtual V_USA_STATE V_USA_STATE { get; set; }
}
joym8
  • 4,014
  • 3
  • 50
  • 93

2 Answers2

1

Apparently, the default code-generation strategy for Entity Framework does not generate Data Annotation attributes like Required. However, you can use a custom T4 template in conjunction with your entity model in order to do this. See the related answer here: Where are the Entity Framework t4 templates for Data Annotations?

Community
  • 1
  • 1
luksan
  • 7,661
  • 3
  • 36
  • 38
1

C# has value types and reference types. String is a reference type, and inherently can already be null. Int, on the other hand, is a value type and has no concept of null. So C# introduced a nullable type structure which wraps value types, System.Nullable. In other words, if you have an int that may need to be null, you need to declare it as Nullable<int> (or int? for short). However, because String is a reference type and can already be null, there's no reason to declare Nullable<string>.

It's not a matter of trying to match up the types with your database null constraints; it's simply a matter of allowing a property to be null if necessary.

Luksan's answer already addresses the lack of [Required] annotation; I just wanted to clarify why EF appears to differentiate null values on ints but not on strings.

Dan A.
  • 2,914
  • 18
  • 23
  • I don't suppose EF is smart enough to figure out that a value on the business end of an outer join might be null. Do you fix these up yourself in the generated classes? – Robert Harvey Jan 26 '13 at 20:17
  • 2
    I had never really thought about outer joins from an EF perspective before (I'm still relatively new to EF myself). But I found this SO question which I think answers it quite nicely: http://stackoverflow.com/questions/1770586/is-an-outer-join-possible-with-linq-to-entity-framework – Dan A. Jan 27 '13 at 05:30