Is there a way to specify .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None) as a decorator to my entity? - asp.net

I have the following class. I was using a mapping file but I would not like to decorate the class with the different options. I already have in my mapping file:
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
How can I set this or set another option of DatabaseGeneratedOption by decorating the class? I looked at the Intellisense options but can't find one for this all I can find is [DatabaseGenerated()] and I am not sure if that's correct or how to set that option:
[DatabaseGenerated()]
public class ContentType : Entity
{
public ContentType()
{
this.Contents = new List<Content>();
}
[Key]
public int ContentTypeId { get; set; }
public string Name { get; set; }
public virtual ICollection<Content> Contents { get; set; }
}

DatabaseGenerated is Property and Field specific attribute. You can't add it to a class, only specific properties or fields.

Related

How to specify default property values for owned entity types in Entity Framework Core 2.0?

I have a simple POCO type, say something like
public class OwnedEntity {
public string stringProperty { get; set; }
public decimal decimalProperty { get; set; }
public bool boolProperty { get; set; }
public int intProperty { get; set; }
}
and an actual entity with an OwnedEntity reference
public class SomeEntity {
public string Id { get; set; }
public OwnedEntity OwnedEntity { get; set; }
}
I set up the relationship like described in the documentation using EF Core's Fluent API:
protected override void OnModelCreating (ModelBuilder builder) {
base.OnModelCreating (builder);
builder.Entity<SomeEntity> ().OwnsOne (e => e.OwnedEntity);
}
I can't find anything on how to define default-values for all the properties of OwnedEntity. I tried to initialize the properties like this:
public class OwnedEntity {
public string stringProperty { get; set; } = "initial"
public decimal decimalProperty { get; set; } = -1M;
public bool boolProperty { get; set; } = false;
public int intProperty { get; set; } = -1;
}
but with no effect. Same goes with the [DefaultValueAttribute] (but that was to expect since it's explicitly mentioned).
There's a bit of information on how to handle initial values for regular entities:
modelBuilder.Entity<SomeOtherEntity>()
.Property(e => e.SomeIntProperty)
.HasDefaultValue(3);
But since I'm facing an Owned Entity Type, I can't access the type via Entity<T>.
Is there a way of doing what I'm looking for?
Some things worth mentioning:
I have a solid amount of specific entities where most of them are using the OwnsOne relation
Declaring all OwnedEntity-properties in a base class is not an option since not all the entities have those properties
I`m using EF Core 2.0.3 and ASP.NET Core MVC 2.0.4
Edit:
Originally, I wanted to have newly created SomeEntity instances to come with preset properties for all of the 'embedded' SomeEntity.OwnedEntity properties.
But looking at how my associated controller works, it all makes sense... I have the following methods for the 'Create' operation:
[HttpGet]
public IActionResult Create () {
return View (nameof (Create));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create (SomeEntity model) {
context.Add (model);
await context.SaveChangesAsync ();
// redirect etc.
}
Which means that no object is created for the [HttGet] overload of Create and all the HTML inputs linked to properties (via asp-for) are initially empty. Okay. So I guess the proper way of doing this is to manually create a new instance of SomeEntity and pass it to the Create view like this:
[HttpGet]
public IActionResult Create () {
return View (nameof (Create), new SomeEntity());
}
Is this the right approach then or are there some more things to keep in mind?
Assuming you understand what EF Core Default Values are for, and just looking for equivalent of Entity<T>().Property(...) equivalent.
The owned entities are always configured for each owner type by using the ReferenceOwnershipBuilder<TEntity,TRelatedEntity> class methods. To access this class you either use the result of OwnsOne method, or use the OwnsOne overload taking second argument of type Action<ReferenceOwnershipBuilder<TEntity,TRelatedEntity>>.
For instance, using the second approach:
builder.Entity<SomeEntity>().OwnsOne(e => e.OwnedEntity, ob =>
{
ob.Property(e => e.stringProperty)
.HasDefaultValue("initial");
ob.Property(e => e.decimalProperty)
.HasDefaultValue(-1M);
// etc.
});

Unable to find a default constructor to use for type Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.DynamicViewData

I am getting this error when trying to Deserialize the string from the redis cache using Newtonsoft.Json.
where HeaderTopViewComponent is model class of one of my view component ""
like: JsonConvert.DeserializeObject<HeaderTopViewComponent>(cacheValue.Result.ToString());
Unable to find a default constructor to use for type Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.DynamicViewData. Path 'ViewBag', line 1, position 340.
Output string :
{"ShowTopheaderSection":true,"PageHeader":"MSHSL","FriendlyURL":"/MSHSL","leagueList":[{"leagueId":0,"FriendlyURL":"/","leaguename":"--Select--"},{"leagueId":3,"FriendlyURL":"/MSHSL","leaguename":"MSHSL"},{"leagueId":4,"FriendlyURL":"/CHSAA","leaguename":"CHSAA"}],"HttpContext":null,"Request":null,"User":null,"RouteData":null,"ViewBag":{},"ModelState":{},"Url":null,"ViewComponentContext":{"Arguments":null,"HtmlEncoder":null,"ViewComponentDescriptor":{"DisplayName":null,"FullName":null,"Id":"9882d08a-1c50-4c59-8a30-2d9c843957e9","ShortName":null,"TypeInfo":null,"MethodInfo":null},"ViewContext":{"FormContext":null,"ClientValidationEnabled":false,"Html5DateRenderingMode":0,"ValidationSummaryMessageElement":null,"ValidationMessageElement":null,"ViewBag":{},"View":null,"ViewData":{},"TempData":null,"Writer":null,"ExecutingFilePath":null,"ActionDescriptor":null,"HttpContext":null,"ModelState":{},"RouteData":null},"ViewData":{},"Writer":null},"ViewContext":{"FormContext":null,"ClientValidationEnabled":false,"Html5DateRenderingMode":0,"ValidationSummaryMessageElement":null,"ValidationMessageElement":null,"ViewBag":{},"View":null,"ViewData":{},"TempData":null,"Writer":null,"ExecutingFilePath":null,"ActionDescriptor":null,"HttpContext":null,"ModelState":{},"RouteData":null},"ViewData":{},"ViewEngine":null}
I have fix it by adding some tag in my viewcomponent modal class and get set property like
[JsonObject(MemberSerialization.OptIn)] and [JsonProperty]
//Tag to add only selected property when Deserialize or Serialize using Newtonsoft
[JsonObject(MemberSerialization.OptIn)]
public class HeaderTopViewComponent:ViewComponent
{
#region //Property//
[JsonProperty]
public bool ShowTopheaderSection { get; set; }
[JsonProperty]
public string PageHeader { get; set; }
[JsonProperty]
public string FriendlyURL { get; set; }
[JsonProperty]
And now its working

Entity Framework 5 - code first array navigation property one to many with Interface Type

These are my classes:
public class Post : IPost
{
public int Id { get; set; }
public virtual int[] DuplicateOf { get; set; }
public virtual ICommentInfo[] Comments { get; set; }
}
public class CommentInfo : ICommentInfo
{
public virtual string Author { get; set; }
public virtual int Id { get; set; }
public virtual string Text { get; set; }
public virtual int PostId{ get; set; }
[ForeignKey("PostId")]
public virtual Post Post { get; set; }
}
With this CommentConfiguration added to OnModelCreate():
HasRequired(c => c.Post)
.WithMany(b=>(ICollection<CommentInfo>) b.Comments)
.HasForeignKey(b=>b.PostId)
.WillCascadeOnDelete(true);
I really cannot understand why the property Comments is always null, and why EF doesn't initialize it since it's virtual.
I tried disabling lazy loading too, but when i try loading the navigation property with context.Post.Include("Comments") an error tells me that "There is not a navigation property called Comments".
So I tried using Entity Framework Power Tools Beta 3 to see the Entity Data Model, and I discovered that there is not a navigation end for table "Post" even if there is the relationship between the two tables and there's the Comment table end too.
I sincerly don't know which way to turn, could be a problem of Array?? Should I use an Icollection property??
Though I cannot change the type of that property because Post is implementing an Interface.
Every sample I look at is clear and easy to make work. Please help me.. Thank you in advance.
EDIT:
This is what I changed after looking at the link I posted yesterday.
public class Post : IPost
{
public int Id { get; set; }
public virtual int[] DuplicateOf { get; set; }
public virtual ICollection<CommentInfo> Comments { get; set; }
ICommentInfo[] IPost.Comments {
get { return Comments ; }
set { Comments = (CommentInfo[])value; } }
}
The exception is: System.ObjectDisposedException :The ObjectContext instance has been disposed and can no longer be used for operations that require a connection and raises when the application tries to get the Comments.
If I remove the virtual key the exception disappear but the property remain always null and the values don't persist in any way.
EDITv2
I've solved my problem adding a new property and map my old property to it.
public class Post : IPost
{
public int Id { get; set; }
public virtual int[] DuplicateOf { get; set; }
public ICommentInfo[] Comments
{
get { return ListComments.ToArray(); }
}
public List<CommentInfo> ListComments {get;set;}
}
In my PostConfiguration OnModelCreate() I used the ListComments property as a navigation property like this:
HasMany(b => b.ListComments)
.WithRequired(c=>c.Post)
.HasForeignKey(c=>c.PostId)
.WillCascadeOnDelete(true);
Now it perfectly works, it was simpler than I expected and when I try to receive the Comments Collection, if I include the "ListComments" property, I get the array of Post.
Thank you for your help!
I can't access the link in your comment, but I assume you changed
public virtual ICommentInfo[] Comments { get; set; }
into the common way to define navigation properties:
public virtual ICollection<CommentInfo> Comments { get; set; }
because entity framework does not support interfaces in its conceptual model.
The exception about the disposed context means that you access this property after fetching Post objects from the database and disposing the context. This triggers lazy loading while the connection to the database is lost. The solution is to use Include:
var posts = context.Posts.Include(p => p.Comments).Where(...)
Now posts and comments are fetched in one go.

Map all properties of a class using reflection

I have two domain classes
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string HouseName { get; set; }
public string StreetName { get; set; }
public string PinCode { get; set; }
}
I want to map object of Employee class to another class.
I am using reflection to map empData object to another object. The code i used is
private void GetValues(object empData)
{
System.Type type = empData.GetType();
foreach (PropertyInfo pInfo in type.GetProperties())
{
//do some stuff using this pInfo.
}
}
I could easily map all the properties except the Address property in the emp object which is an object of another class.
So how can i map all the properties irrespective of its type ? i.e, if address contains object of another class it should also get mapped.
Can't you use AutoMapper for mapping classes?
You can know the type of property you are mapping by
if (propertyInfo.PropertyType == typeof(Address))
{ // do now get all properties of this object and map them}
Assuming that you want to be able to do this on any type of object and not just this specific one, you should use some sort of recursive solution. However if it's just for this object - why are you even using reflection? To me it just adds unnecessary complexity to something as simple as mapping six properties to another set of objects.
If you want to get more concrete help with code examples, you'll have to give us some more context. Why does a method named "GetValues" has a return type of void? I have a hard time coding up an example with that in mind. :)

EF 4.1 messing things up. Has FK naming strategy changed?

I've just installed the new Entity Framework 4.1 NuGet package, thus replacing the EFCodeFirst package as per NuGet intructions and this article of Scott Hanselman.
Now, imagine the following model:
public class User
{
[Key]
public string UserName { get; set; }
// whatever
}
public class UserThing
{
public int ID { get; set; }
public virtual User User { get; set; }
// whatever
}
The last EFCodeFirst release generated a foreign key in the UserThing table called UserUserName.
After installing the new release and running I get the following error:
Invalid column name 'User_UserName'
Which of course means that the new release has a different FK naming strategy. This is consistent among all other tables and columns: whatever FK EFCodeFirst named AnyOldForeignKeyID EF 4.1 wants to call AnyOldForeignKey_ID (note the underscore).
I don't mind naming the FK's with an underscore, but in this case it means having to either unnecessarily throw away the database and recreate it or unnecessarily renaming al FK's.
Does any one know why the FK naming convention has changed and whether it can be configured without using the Fluent API?
Unfortunately, one of the things that didn't make it to this release is the ability to add custom conventions in Code First:
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-release-candidate-available.aspx
If you don't want to use the fluent API to configure the column name (which I don't blame you), then most straight forward way to do it is probably using sp_rename.
Why don't you do the following?
public class User
{
[Key]
public string UserName { get; set; }
// whatever
}
public class UserThing
{
public int ID { get; set; }
public string UserUserName { get; set; }
[ForeignKey("UserUserName")]
public virtual User User { get; set; }
// whatever
}
Or, if you don't want to add the UserUserName property to UserThing, then use the fluent API, like so:
// class User same as in question
// class UserThing same as in question
public class MyContext : DbContext
{
public MyContext()
: base("MyCeDb") { }
public DbSet<User> Users { get; set; }
public DbSet<UserThing> UserThings { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserThing>()
.HasOptional(ut => ut.User) // See if HasRequired fits your model better
.WithMany().Map(u => u.MapKey("UserUserName"));
}
}

Resources