I have the following migration definition:
public override void Up()
{
AddColumn("dbo.MyTable", "MyEnum", c => c.Int(defaultValue: 0));
}
This will add my Enum to the Sql-Table during the migration. I'm using TPH and this enum is only member of a specified type, so EF will automaticly makes it nullable.
Question:
After the migration all columns have the value of "null". Instead of 0.
I would expect that only the table entries which use this enum type will have the default value of 0.
Related
How can I use Relate and unique using aqueduct ORM?
In my code I want that the userapp be unique?
If I try to put #Column(unique: true) I receive a error like this:
*** Relationship 'userapp' on '_Professional' cannot both have 'Column' and 'Relate' metadata. To add flags for indexing or
nullability to a relationship, see the constructor for 'Relate'.
My code below:
class Professional extends ManagedObject<_Professional> implements _Professional {}
class _Professional {
#primaryKey
int id;
#Relate(#professionals)
Userapp userapp;
#Column(defaultValue: 'true')
bool active;
ManagedSet<ProfessionalSpecialty> professionalSpecialties;
}
Whether the foreign key column underlying userapp is unique or not is determined by the inverse relationship property. In this case, the inverse is Userapp.professionals.
If Userapp.professionals is of type Professional, then a unique constraint is added to userapp; this is a 'has-one' relationship.
If Userapp.professionals is of type ManagedSet<Professional>, no unique constraint is applied; this is a 'has-many' relationship.
I'd guess that because you are using the plural form (professionals) that you are declaring a ManagedSet<Professional>. Change the declaration in the _Userapp table definition and make sure your inverse matches in _Professional:
class _Userapp {
...
Professional professional;
}
class _Professional {
...
#Relate(#professional)
Userapp userapp;
}
I got the following class in my models
public DateTime DateTimePosted { get; set; }
and it's causing this error while DB migrations
"Cannot insert the value NULL into column 'DateTimePosted"
but when I allow nulls in my model this way
public DateTime? DateTimePosted { get; set; }
then migration is succesfull , but column in Db stays nullable,
but when I'm trying to pass it to Db by Seed method it works fine.
This is my controller
public ActionResult AddApartment()
{
return View(new Apartment { DateTimePosted = DateTime.Now });
}
My question is
How to pass to DB date and time of posted data
You get this error because you are trying to add new non-nullable column on a table that already contains some data. Because you're adding a non-nullable column, DB Migrations doesn't know which value to set for the new column to thos already inserted lines into your table. To fix that you have two solutions:
Making DateTimePosted a nullable data by using DateTime?
Modify your newly generated migration file by locating the line that add your new column and add set the defaultValueSql parameter like below :
The code:
AddColumn("YOUR_TABLE_NAME", "DateTimePosted",
c => c.DateTime(nullable: false, defaultValueSql: "GETUTCDATE()")
);
Using EF code first want to control the name of the genereted column WHEN REFERENCING SELF. Tried [ForeignKey] and [Column] attributes. [Column] does not work and [ForeignKey] forces a relationship that seems to cause a problem. I have used [ForeignKey] attribute to set the name of a column in another class/table connected to this one.
Have
public class Episodes
{
public long ID {get; set;}
// ... other properties
public List<Episodes> Children { get; set; }
}
want a table (ID, ..., ParentID) - get a table (ID, ..., Episode_ID)
If you don't have the foreign key column exposed as property in your entity class you can define the column name only with Fluent API:
modelBuilder.Entity<Episodes>()
.HasMany(e => e.Children)
.WithOptional()
.Map(m => m.MapKey("ParentID"));
I assume that the parent is optional (ParentID is a nullable column in the DB table) because, I guess, there should be some "root" in the tree, i.e. an episode that doesn't have a parent anymore, hence at least for this episode the ParentID column must be NULL.
I am trying to find examples or documentation related to DbMigration and ColumnModel.
I simply want to specify width of string propery in DBMigration Up method
E.g.
AddColumn("Districts", "Code", c => c.String());
will create nvarchar(max) - and I want to specify maxlength(20) for example.
Is this integrated with EntityTypeConfiguration or I have to add also manually
this.Property(t => t.Name).HasColumnName("Code").IsRequired().HasMaxLength(20);
MSDN help doesn't give any examples and walkthrough on ef4 blog covers only basics
If you use AddColumn directly you can simply use:
AddColumn("Districts", "Code", c => c.String(maxLength: 20));
If you define max length in EntityTypeConfiguration (which is correct approach) EF Migration will handle it for you.
The configuration of the columns should be done as data annotations. To make a string column have a specific width, use the StringLengthAttribute:
[Required] // Makes column not null
[StringLength(20)] // Makes it a nvarchar(20) instead of nvarchar(max)
public string SomeString {get;set;}
I have defined a model class with an ID column set as [Key], on an existing database table. the table has the field defined as primary key, int, not null. It is NOT and identity column.
When creating a new record in code, I am setting the ID column (to an unique value) in code before calling the SaveChanges() method.
The method returns with the error:
Cannot insert the value NULL into column 'xxx_id', table
'xxx.dbo.xxxxxx'; column does not allow nulls. INSERT fails. The
statement has been terminated.
It seems that EF assumes that the ID column is an Identity column and therefore doesn't pass the ID in the SQL call to the database.
Is there a way to define the ID column to tell EF that is it not an Identity column and to pass the value in the SQL call
You need to specify the DatabaseGeneratedOption for the property. In this case, the DatabaseGeneratedOption should be None.
See: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.databasegeneratedoption%28v=vs.103%29.aspx
I have usually done this with fluent coniguration like:
Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
.. but it looks like this can also be specified with an attribute. See http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.databasegeneratedoption%28v=vs.103%29.aspx
[DatabaseGenerated(DatabaseGeneratedOption.None)]