how to update .edmx file without effecting all the other model classes? - entity-framework

how to update .edmx file without effecting all the other model classes?
when I update the edmx file it recreates all the other classes and this is a problem for me because I made some changes on the other classes so how can I modify it without affecting the other classes.
For example this is one of my classes
public partial class company
{
public company()
{
this.Departments = new HashSet<department>();
this.CustomersOfTheCompany = new HashSet<company_customers>();
this.CompaniesTheCompanyCustomerFor = new HashSet<company_customers>();
this.CustomerProjectDetails = new HashSet<cus_pro_connector>();
this.CompanyAsSupplier = new HashSet<company_suppliers>();
this.CompanyAsCustomer = new HashSet<company_suppliers>();
this.Tickets = new HashSet<oneTimeAuthenticationTicket>();
}
[Required(ErrorMessage = "Company name is required")]
[StringLength(200, MinimumLength = 3, ErrorMessage = "Length Of The Company Name Should Be More Than Three Letters")]
public string CompanyName { get; set; }
[Required]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
[Required]
public int Country { get; set; }
public int company_id { get; set; }
public string Logo { get; set; }
public string Description { get; set; }
private CompanyDTO _CDTO = new CompanyDTO();
public CompanyDTO CDTO { get { return this._CDTO; } set { this._CDTO = value; } }
public virtual ICollection<department> Departments { get; set; }
public virtual country CountryOfTheCompany { get; set; }
public virtual ICollection<company_customers> CustomersOfTheCompany { get; set; }
public virtual ICollection<company_customers> CompaniesTheCompanyCustomerFor { get; set; }
public virtual ICollection<cus_pro_connector> CustomerProjectDetails { get; set; }
public virtual ICollection<company_suppliers> CompanyAsSupplier { get; set; }
public virtual ICollection<company_suppliers> CompanyAsCustomer { get; set; }
public virtual ICollection<oneTimeAuthenticationTicket> Tickets { get; set; }
}
so when I modify the .edmx the class attributes will no longer be available.

It is not possible to retain edits to generated files when you re-generate them. If you need to apply attributes to generated code, there is a MetadataType mechanism that allows you to specify validation attributes in another partial class.
See this other answer or MSDN for further information on this.

I don't understand your example - But I will explain here:
Let's say you have the following Entity Models:
And the User.cs looks like this:
public partial class User
{
public User()
{
this.UserWindows = new HashSet<UserWindow>();
}
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public virtual ICollection<UserWindow> UserWindows { get; set; }
}
Add a new file and call it Extensions.cs, then create a New Partial Class in this File:
Then you can Add Properties to this Class:
public partial class User
{
public int NewUserId { get; set; }
}
And whenever you create a New User Object you will see your new Properties:
Similarly you can do this for UserWindow.cs
Extensions.cs:
public partial class User
{
public int NewUserId { get; set; }
}
// Similarly you can do
public partial class UserWindow
{
public string MyNewProperty { get; set; }
}
Then

Related

LINQ query throw exception on FirstOrDefault method

I'm using EF core, and I have a many-to-many relationship between two entity
IotaProject <--> User
Here's entities & dto related to the question
public class IotaProject
{
[Key]
public int Id { get; set; }
[Required]
public string ProjectName { get; set; }
[Required]
public DateTime Create { get; set; }
public ICollection<ProjectOwnerJoint> Owners { get; set; } = new List<ProjectOwnerJoint>();
}
public class ProjectOwnerJoint
{
public int IotaProjectId { get; set; }
public IotaProject IotaProject { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
public class User
{
[Key]
public int Id { get; set; }
[Required]
public string FullName { get; set; }
[Required]
public string ShortName { get; set; }
[Required]
public string Email { get; set; }
public ICollection<ProjectOwnerJoint> OwnedProjects { get; set; } = new List<ProjectOwnerJoint>();
}
public class ApplicationDbContext : DbContext
{
public DbSet<IotaProject> IotaProjects { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<ProjectOwnerJoint> ProjectOwnerJoint { get; set; }
}
public class IotaProjectDisplayDto
{
public int Id { get; set; }
public string ProjectName { get; set; }
public DateTime Create { get; set; }
public UserMinDto Owner { get; set; }
public int Count { get; set; }
public IEnumerable<UserMinDto> Reviewers { get; set; }
}
public class UserMinDto
{
public int Id { get; set; }
public string FullName { get; set; }
public string ShortName { get; set; }
}
Following LINQ is the problem, the LINQ purpose is to convert IotaProject to IotaProjectDisplayDto, and key part is that Owners property of IotaProject is ICollection and Owner property in IotaProjectDisplayDto is just one single element UserMinDto, so I only need to get the first element of IotaProject's Owners and that's FirstOrDefault() comes.
IEnumerable<IotaProjectDisplayDto> results = _db.IotaProjects.Select(x => new IotaProjectDisplayDto
{
Id = x.Id,
ProjectName = x.ProjectName,
Create = x.Create,
Owner = x.Owners.Select(y => y.User).Select(z => new UserMinDto { Id = z.Id, FullName = z.FullName, ShortName = z.ShortName }).FirstOrDefault()
});
return results;
it throws run-time exception
Expression of type 'System.Collections.Generic.List`1[ToolHub.Shared.iota.UserMinDto]' cannot be used for parameter
of type 'System.Linq.IQueryable`1[ToolHub.Shared.iota.UserMinDto]'
of method 'ToolHub.Shared.iota.UserMinDto FirstOrDefault[UserMinDto](System.Linq.IQueryable`1[ToolHub.Shared.iota.UserMinDto])' (Parameter 'arg0')
I'm guessing it's probably related to deferred execution, but after read some posts, I still can't resolve it.
Any tips would be appreciated.
Right now, the only way I can get this work is I change type of Owner property in IotaProjectDisplayDto into IEnumrable, which will no longer need FirstOrDefault() to immediate execution. And later on, I manually get the first element in the client to display.
This issue happened in Microsoft.EntityFrameworkCore.SqlServer 3.0.0-preview7.19362.6
I end up downgrade to EF core stable 2.2.6 as Ivan suggested in comment, and everything works fine.

EF 6 Code First Mapping one-to-many

Can someone please help me with mapping the following hierarchy with EF 6 code first? I can find anything useful for the below example in the documentation.
namespace Contacts {
public class Person
{
public Person()
{
this.Emails = new HashSet<Email>();
}
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Email> Emails { get; set; }
}
public class Company
{
public Company()
{
this.Emails = new HashSet<Email>();
}
public long Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Email> Emails { get; set; }
}
public class Email
{
public string Value { get; set; }
public string Label { get; set; }
public string TargetId { get; set; }
public string TargetType { get; set; }
}
}
TargetType can be set to Company or Person depending on the entity that contains the Email instance.
DB Schema:

EF6 generates all the entity classes (tt .cs) in single file (eg. model.cs) and not as separate .cs file

I am using EF6. I have 2 tables Events and Users for which I used database first approach to generate the EDMX models and entity classes. Everything works fine but the entity classes are coming under a single file in this case EventSample.cs(shown below). I am not getting separate files for each entity as Event.cs and User.cs. Please let me know if this is correct and if not how to rectify it?
public partial class Event
{
public Event()
{
this.Users = new HashSet<User>();
}
public int Id { get; set; }
public string Title { get; set; }
public System.DateTime Time { get; set; }
public string Location { get; set; }
public string Description { get; set; }
public int Creator_Id { get; set; }
public virtual User User { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public partial class User
{
public User()
{
this.Events = new HashSet<Event>();
this.Events1 = new HashSet<Event>();
}
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public virtual ICollection<Event> Events { get; set; }
public virtual ICollection<Event> Events1 { get; set; }
}

EF Data Annotation - Foreign Key - How to Customize

My issue is the following. I have a Model for an Address table as follows.
public partial class ADDRESS
{
public ADDRESS()
{
this.ADDRESS_ID = Guid.NewGuid();
}
public Guid ADDRESS_ID { get; set; }
public string ADDRESS_LINE { get; set; }
public string CITY { get; set; }
public Guid? STATE_ID { get; set; }
public string ZIP { get; set; }
}
This ADDRESS model is used throughout my application and has different validation requirements depending on where it is placed within a form.
I am wondering if there is a way to customize the data annotations. For example, the ADDRESS_LINE and CITY properties are required for OCCUPATION_ADDRESS but not required for WORK_LOCATION_ADDRESS.
public class OCCUPATION_DETAILS
{
public string COMPANY_NAME { get; set; }
public string JOB_TITLE { get; set; }
etc...
public Guid OCCUPATION_ADDRESS_ID { get; set; }
public virtual ADDRESS OCCUPATION_ADDRESS { get; set; }
public WORK_LOCATION_ID { get; set; }
public virtual ADDRESS WORK_LOCATION_ADDRESS { get; set; }
}
Or it could be that basic validation is the same (zip has to be 5 digits), but I need to adjust the "DisplayName" that is used to match the label of the form it is within.
Trying to minimize the amount of copied models I have set up; otherwise maintenance will be a nightmare.
you can achieve this by using the idea of inheritance
how?
public abstract class ADDRESS
{
public ADDRESS()
{
this.ADDRESS_ID = Guid.NewGuid();
}
public Guid ADDRESS_ID { get; set; }
public string ADDRESS_LINE { get; set; }
public string CITY { get; set; }
public Guid? STATE_ID { get; set; }
public string ZIP { get; set; }
}
public parital class OCCUPATION_ADDRESS: ADDRESS,IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if(string.IsNullOrWhiteSpace(ADDRESS_LINE))
yield return new ValidationResult("Address line is required!",new string[]{"ADDRESS_LINE"});
}
}
public parital class WORK_LOCATION_ADDRESS: ADDRESS,IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
}
}
// and your Occupation details class will be like: instead of ADDRESS you will use the corresponding derived classes
public class OCCUPATION_DETAILS
{
public string COMPANY_NAME { get; set; }
public string JOB_TITLE { get; set; }
etc...
public Guid OCCUPATION_ADDRESS_ID { get; set; }
public virtual OCCUPATION_ADDRESS OCCUPATION_ADDRESS { get; set; }
public WORK_LOCATION_ID { get; set; }
public virtual WORK_LOCATION_ADDRESS WORK_LOCATION_ADDRESS { get; set; }
}
and the inheritance should be Table per Hierarchy (TPH)
for more information about TPH check this Table per hierarchy
hope that this will help you
regards

I get UpdateException when i try to Update a collection property

I am in an MVC4 application and i am using EF CodeFirst.
When I try to run the following code:
public void Autorizare(int cerereId, Persoana persoana)
{
var cerere = _db.Cereri.Find(cerereId);
cerere.Autorizare.Add(persoana);
_db.SaveChanges();
}
I get an error like this:
Entities in 'CerereDbContext.Persoane' participate in the 'Actiune_Executanti' relationship. 0 related 'Actiune_Executanti_Source' were found. 1 'Actiune_Executanti_Source' is expected.
i have tried Entity(Actiune).State = EntityState.Modified, but no results.
I have a main POCO:
public class Cerere
{
public int Id { get; set; }
...
public virtual ICollection<Actiune> Actiuni { get; set; }
...
}
the Actiune class looks like this
public class Actiune
{
public int Id { get; set; }
public DateTime Data { get; set; }
public String Nume { get; set; }
public virtual ICollection<Persoana> Executanti { get; set; }
public String Stadiu { get; set; }
public String Obs { get; set; }
}
And Persoana:
public class Persoana
{
public int Id { get; set; }
public DateTime Data { get; set; }
public String Nume { get; set; }
}
From your model the Cerere does not have a property named Autorizare; however it does have one named Actiuni. Which is of type Actiune not Persoana which is what you are trying to add to it. Please post the rest of the Class Definition.