I am EF new learner, i have some questions to ask:
1.
I don't understand what does virtual mean in for example one to many, i give an example:
one question can have many options for e.g.
public class Question
{
public int QuestionId { get; set; }
public string Title { get; set; }
public virtual List<Option> Options { get; set; }
}
public class Option
{
public int OptionId { get; set; }
public string OptionText { get; set; }
public virtual Question Question { get; set; }
}
but what does the "2" virtual mean, because if i delete the virtual in this line:
public virtual List<Option> Options { get; set; }, i didn't find any differences, it works well as one to many, so can you explain me very clearly and easily what the 2 virtual mean, if it's override, override what?
2.
I don't know when we should use API fluent, for e.g. the previous one to many ex. without api fluent, it's still a one to many Relationship, so please just tell me when we should use it ? in which occasions for example.
3.
in the API fluent, i know "withmany" and "hasmany" together, they mean "many to many", and what's "withrequired? isoptional? "
I think I can answer following points:
EF define all navigation property virtual, so that EF will at runtime create a new class (dynamic proxy) derived from your Brand class and use it instead. This new dynamically created class contains logic to load navigation property when accessed for the first time. This feature is called lazy loading (or better transparent lazy loading).
See the following link for more detail
Entity Framework 4.1 Virtual Properties
2.When to use fluent API
When working with Code First, you define your model by defining your domain CLR classes. By default, the Entity Framework uses the Code First conventions to map your classes to the database schema. If you use the Code First naming conventions, in most cases you can rely on Code First to set up relationships between your tables based on the foreign keys and navigation properties that you define on the classes. If you do not follow the conventions when defining your classes, or if you want to change the way the conventions work, you can use the fluent API or data annotations to configure your classes so Code First can map the relationships between your tables.
http://msdn.microsoft.com/en-us/data/jj591620.aspx
3.See the following link to know What is .WithRequired and .WithOptional options
What part does the .WithRequired play in an EF Fluent API?
Related
I'm starting to use EFCore in a UWP app with SQLite. I've declared the classes that I want stored in the database. I've then declared various DbSets and the OnConfiguring override:
public class DatabaseContext : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Relationship> Relationships { get; set; }
public DbSet<SourceDescription> SourceDescriptions { get; set; }
public DbSet<Agent> Agents { get; set; }
public DbSet<Event> Events { get; set; }
public DbSet<Document> Documents { get; set; }
public DbSet<PlaceDescription> PlaceDescriptions { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Filename=Testing.db");
}
}
In the Package Manager Console, I then go:
Add-Migration 2017-06-23
and it creates the code to then build the database. HOWEVER, that code is missing some of the top-level tables. Some of them are there but some aren't and I can't see/figure out what is causing this. No errors are generated and I cannot find a pattern to determine why the missing tables are missing.
Further information:
There are 29 classes defined in my code. The migration code creates 24 tables.
Of the 5 "missing" classes, 4 of them are derived from Subject which, in turn, derives from Conclusion. The fifth is the Conclusion class. Since the migration code "merges" the properties from each of the derived classes, I'm not surprised that the Conclusion class doesn't have its own table as there is no direct use of it as a class.
With the exception of the Conclusion class, the other 4 classes are only referenced in the DbSet properties (as opposed to be used in properties in other classes). As noted above, the Document class is derived from another class, so it isn't derived classes that is the common factor.
It isn't that some of the classes are partial classes.
I can't spot anything about the properties in the classes that is a common factor. For example, the Person class has List a couple of times but so does the Agent class and that does appear in the migration code.
Any suggestions on what I can look for or if this is a known issue?
To clarify, the answer provided by Ivan is that EF Core sees the four classes that are derived from the Subject class and builds a table for the Subject class that includes all of the properties for those derived classes. There is then a Discriminator column added to the Subject class that indicates which derived class this is for.
http://www.learnentityframeworkcore.com/inheritance/table-per-hierarchy is a good article for explaining it.
An interesting approach to designing database tables that I hadn't come across before. I live and learn :)
So if I have the following entity:
public class Guest
{
public int GuestId { get; set; }
public bool HasCheckedIn { get; set; }
// child/related entities
public Person Person { get; set; }
public Address Address { get; set; }
public Phone Phone { get; set; }
}
Please forgive/correct me if some of the terminology I use is not correct...
Assume we have turned off Navigation Properties which would automatically populate the child entities such as Person and Address.
If my website is calling the WebApi for specific data, sometimes it might need the 'full' Guest object with all of the child entities, in which case it might call the appropriate method in the Business Layer to backfill the object. In other cases, to keep the request light we might just want a 'shell' or 'brief' of the Guest with just the basic data that the underlying table would hold such as HasCheckedIn and all the child entities to just be null.
So what is the suggested approach here for the Api Controller? Should there just be one Persons Controller who's Get method is really a proxy to the GetFull method in the BLL Person class and then have a separate PersonsBrief Controller who's Get method is really a proxy to the GetBrief method in the BLL Person class? Or should this be one method in the Persons Controller which takes in a boolean for IsBrief or something?
Both approaches have merit but it may actually be clearer to separate the summary and details into separate resources. It seems like your use cases between the two variations are distinct, which to me suggests that you should separate your resources accordingly. In other words, implement two separate controller methods, one for "guest details" and another for "guest summary".
I'm new to MVC and I'm trying to figure out how to implement business logic in the auto generated Entities in an MVC project.
I know that if I create my own Model class I can put [Required] and other attributes on the fields but there doesn't seem to be an option to do that in the .edmx file.
Is there something I'm missing here?
Should I be creating my own classes that use the entities and put the logic in there?
It seems like there should be a way for me to do less work.
Thanks!
This can be achieved by using the buddy-class functionality in .NET implemented specifically for this reason. Once you have created your entities in your .ebmx file you can create partial classes to accompany your entities which define your business rules in a 'buddy class'.
[MetadataType(typeof(ProductMetadata))]
public partial class Product {
internal sealed class ProductMetadata {
[DisplayName("Name")]
[Required]
public string Name { get; set; }
[DispayName("Price")]
[Required, Range(1,10000)]
public decimal Price { get; set; }
[DisplayName("Description")]
public string Description { get; set; }
}
}
In the example above, assume that you already have a "Product" type defined in your object context which has properties for "Name", "Price", and "Description". So long as the buddy class type referenced by the MetadataTypeAttribute has matching property names, the attributes applied to the properties in the buddy class will be applied to the implementation type.
Note: if there are any property names in the buddy class which do not match the implementation type, you will get a runtime error. You only need to create matching properties in the buddy class for the properties you are interested in applying business rules to; all properties are optional.
I am pretty new to entity framework, but given a simple object like this:
public class Country
{
public string Name { get; set; }
[Key]
public string Code { get; set; }
public bool IsPostalCodeRequired { get; set; }
public ICollection<Province> Provinces { get; set; }
}
returned by a DbContext, the Provinces property is null. If I use the Include method on my linq statement to include provinces, then it works. But I was wondering if there's a way to load them when I actually access the property? I know there's performance concerns to think about here, but I just want to know how to do it.
Thanks,
Make sure ObjectContext.ContextOptions.LazyLoadingEnabled is true. This is the default for a new project.
If using pure POCO entities, lazy loading can't work (think about it). So you can use POCO proxies. Again, this is the default, but making lazy loading work with POCO proxies requires that all the relationship properties are declared virtual, and yours aren't.
Craig said it all. Just wanted to say by default ObjectContext has LazyLoading turned off . Although when you create new .net 4.0 project, the model designer explicitly turns it on for u for .net 4.0 projects. Its turned off because EF needs to preserver legacy behavior of .net 3.5 when lazy loading was not available. However as you may notice that you are using Dbcontext which is new and has no dependency to .net 3.5. Hence LazyLoading would be enabled by default to give you seamless experience.
I want a list of different (derived) object types working with the Default Modelbinder in Asp.net MVC 2.
I have the following ViewModel:
public class ItemFormModel
{
[Required(ErrorMessage = "Required Field")]
public string Name { get; set; }
public string Description { get; set; }
[ScaffoldColumn(true)]
//public List<Core.Object> Objects { get; set; }
public ArrayList Objects { get; set; }
}
And the list contains objects of diffent derived types, e.g.
public class TextObject : Core.Object
{
public string Text { get; set; }
}
public class BoolObject : Core.Object
{
public bool Value { get; set; }
}
It doesn't matter if I use the List or the ArrayList implementation, everything get's nicely scaffolded in the form, but the modelbinder doesn't resolve the derived object type properties for me when posting back to the ActionResult.
What could be a good solution for the Viewmodel structure to get a list of different object types handled? Having an extra list for every object type (e.g. List, List etc.) seems to be not a good solution for me, since this is a lot of overhead both in building the viewmodel and mapping it back to the domain model.
Thinking about the other approach of binding all properties in a custom model binder, how can I make use the data annotations approach here (validating required attributes etc.) without a lot of overhead?
Check out the Derived Type ModelBinder in MvcContrib. This allows you to modelbind to derived types through the process of 'typestamping' - which is handled automatically for you when using the RenderTypedPartial(...) helper. MvcContrib partials maintain binding state across partials so the Name/Id prefixes are properly maintained on a deep object graph. If you use other mechanisms like templates, then you'll need to handle the typestamping yourself. This is explained in the documentation page.
Getting back to your questions and how the derived types are resolved with the ModelBinder, you can register the derived type variations with attributes in a mechanism similar to the WCF KnownTypeAttribute or you can do the registration on startup. Either way, these variations are registered once and held onto for performance considerations.
The model binder also solves this problem in a way that does not interfere with data annotation/validation attributes. They will work as you expect them in any other scenario.