How to get fluent api mapped entity table name EF - entity-framework

I'm having problems getting the mapped table name when using fluent api. When you use data annotations it's easy because you can use the TableAttribute in order to get the table name from an specific entity, but when I use fluent api I can't find a way to do that.
I need it because I'm implementing an audit trail overriding the SaveChanges on the dbContext.
Thanks

I figure it out.
In order to get information about the Entity when using Fluent API I did this:
// get the actual entity Set
// DataSpace.SSpace = Storage part of the model has info about the shape of our tables
var entitySet = workspace.GetItems<System.Data.Entity.Core.Metadata.Edm.EntityContainer>(System.Data.Entity.Core.Metadata.Edm.DataSpace.SSpace)
.SelectMany(e => e.EntitySets).ToList().Where(a => a.Name == entityTypeName).FirstOrDefault();
And finally:
// Get table name
string tableName = entitySet.Table;
Hope this can help others!

Related

Declare Table Name for a model in EF

In EF Core how do you declare the name of the table it will create. Currently when you use "Add-Migration" it uses the name of the model when it create the table. Is there anyway to change that instead of using the name of my model.
Simplest way is to add a TableAttrbiute to your entity classes. Eg
[Table(Name = "customer_orders")]
public class CustomerOrder
{
// ...
}
This can also be done in DbContext.OnModelCreating using the Fluent API.

Dotnet Entity Framework Include without a Foreign Key

I have two models:
Location
Id
FacilityMnemonic
Name
Facility
Id
FacilityMnemonic
Name
Location's FacilityMnemonic can be null. It's possible that the location may have a facility mnemonic that does not have a facility. I need a way to structure these entities so that I can do some form of
_context.Locations.Where(CONDITIONS HERE).Include("Facility").ToList();
And then be able to package that up in a nice json response for my web API. I cannot use a foreign key, however, because the constraint will fail if there is a mnemonic with no matching facility. Having trouble determining the right way to do this with entity framework. Any guidance appreciated.
You cannot use include without relationship in SQL server.
You can use this instead
var list = (from a in _context.Location.Where(CONDITIONS HERE)
from b in _context.Facility.Where(CONDITIONS HERE related to Location).DefaultOrEmpty()
select new Location() {
Id = a.Id,
Name = a.Name,
Facilities = b
}).ToList();

How to use Entity Framework with a database without relationships defined

I am new to EF so please bear with me. I am using Entity Framework with an existing database in which the relationships are not defined.
Using EF, I am able to produce the model, but obviously the 'navigational properties' are not working. Is there a way I can specify the mapping between the entities?
For example, in my Product entity, I have a field CategoryID_fk (maps to Category entity). But since the relationships are not defined, I cannot load a Category while loading a Product entity.
Can someone guide me in this regard?
I do understand that it would be preferable to refactor our database but I am unable to do that now. Thanks in advance.
This link is very useful.http://www.entityframeworktutorial.net/
I think field names are not suitable conventions.Try to change field name as CategoryId or Category_CategoryId .I think it will work
Yes, you can do a group join. Basically you will retrieve Products and Category in separate queries and take an approach as indicated in this answer.
Something along these lines:
var productCategoryList = products.GroupJoin
(
categories,
p=> p.productId,
c=> c.CategoryId,
(p, c) => new ProductCategory
{
//Create your Product Category model here
}
).AsEnumerable();

Entity Framework Core - Get DbContext data model

I need to know information about entities, tables, mappings, keys etc for the given instance of DbContext. In Entity Framework 6 I was writing edmx like this:
System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(dbContext, xmlWriter);
which I then used to build my own data model (this is needed for a tool which supports loading data from different sources). How do I get such information for the new EF Core (previous EF 7)? I could use Reflection, but this will give me only the conceptual schema, while I also need mappings and storage schema. I've been looking through the EF source code for a while now, but don't seem to find any object, that stores all the required data.
This should get you started
using (var ctx = new TestContext())
{
var entityType = ctx.Model.FindEntityType(typeof (Entity_Basic));
var tableName = entityType.SqlServer().TableName;
var columnName = entityType.GetProperties().ToList()[0].SqlServer().ColumnName;
}

DTO/POCO with Entity Framework

I'm using EF5 Model First. I don't really understand what are the auto-generated classes from the EDM. According to some documentation this classes are POCOs but why are they used in the context ?
Assuming I have a Student entity, then I get a Student POCO class and a DbSet StudentSet property in my context.
Will this next instructions put a POCO in my database ?
MyContext.StudentSet.Add(johndoe);
MyContext.SaveChanges();
So EF uses POCO to transfer data ? Actually I miss the step when POCO exchange data with entities or DTO and when the entities put data in the database.
The generated classes from the EDM is the ORM / Persistence classes. You use that classes to query / make changes from / to database. You need to translate any DTO object to POCO object when about making changes to database.
ORM is about mapping object to data in database, instead of dealing with insert into syntax to insert record to database in the application, you use StudentSet.Add to add a new data. The johndoe information will be translated into sql syntax, EF will map each property to each column when translating it into query.
The Add method will store the johndoe information as Added in the memory but it will not be executed right away to the database. If you have another Add method, it will be marked as Added too. The moment you call SaveChanges, all the changes will be saved into database by sending a generated query.
The mapping between DTO and EF entity happens before you add the johndoe. You might have another DTO class that is used in the UI. You need to map it manually or using mapper library to create a POCO object from a DTO object. For example:
// studentDto as parameter
var johndoe = new Student
{
Name = studentDto.StudentName,
Age = studentDto.StudentAge
};
MyContext.StudentSet.Add(johndoe);
// studentDto might have another information as well
var johndoeSubject = new Subject
{
Name = studentDto.SubjectName,
Years = studentDto.SubjectYears
};
MyContext.SubjectSet.Add(johndoeSubject);
MyContext.SaveChanges();