Commit f161aaec authored by oshaarru's avatar oshaarru

firs upload

parents
packages
Queries/bin
Queries/obj
*.suo
\ No newline at end of file

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.31101.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Queries", "Queries\Queries.csproj", "{D1776DED-C59A-4F8A-8C31-96EAE15BDF5A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D1776DED-C59A-4F8A-8C31-96EAE15BDF5A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D1776DED-C59A-4F8A-8C31-96EAE15BDF5A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D1776DED-C59A-4F8A-8C31-96EAE15BDF5A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D1776DED-C59A-4F8A-8C31-96EAE15BDF5A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<connectionStrings>
<add name="PlutoContext" connectionString="data source=.\SQLEXPRESS;initial catalog=Pluto_Queries;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
\ No newline at end of file
using System.Collections.Generic;
namespace Queries.Core.Domain
{
public class Author
{
public Author()
{
Courses = new HashSet<Course>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
}
using System.Collections.Generic;
namespace Queries.Core.Domain
{
public class Course
{
public Course()
{
Tags = new HashSet<Tag>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Level { get; set; }
public float FullPrice { get; set; }
public virtual Author Author { get; set; }
public int AuthorId { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public Cover Cover { get; set; }
public bool IsBeginnerCourse
{
get { return Level == 1; }
}
}
}
namespace Queries.Core.Domain
{
public class Cover
{
public int Id { get; set; }
public Course Course { get; set; }
}
}
using System.Collections.Generic;
namespace Queries.Core.Domain
{
public class Tag
{
public Tag()
{
Courses = new HashSet<Course>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
}
using Queries.Core.Repositories;
using System;
namespace Queries.Core
{
public interface IUnitOfWork : IDisposable
{
ICourseRepository Courses { get; }
IAuthorRepository Authors { get; }
int Complete();
}
}
\ No newline at end of file
using Queries.Core.Domain;
namespace Queries.Core.Repositories
{
public interface IAuthorRepository : IRepository<Author>
{
Author GetAuthorWithCourses(int id);
}
}
\ No newline at end of file
using Queries.Core.Domain;
using System.Collections.Generic;
namespace Queries.Core.Repositories
{
public interface ICourseRepository : IRepository<Course>
{
IEnumerable<Course> GetTopSellingCourses(int count);
IEnumerable<Course> GetCoursesWithAuthors(int pageIndex, int pageSize);
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace Queries.Core.Repositories
{
public interface IRepository<TEntity> where TEntity : class
{
TEntity Get(int id);
IEnumerable<TEntity> GetAll();
IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate);
TEntity SingleOrDefault(Expression<Func<TEntity, bool>> predicate);
void Add(TEntity entity);
void AddRange(IEnumerable<TEntity> entities);
void Remove(TEntity entity);
void RemoveRange(IEnumerable<TEntity> entities);
}
}
\ No newline at end of file
// <auto-generated />
namespace Queries.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class InitialMigration : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(InitialMigration));
string IMigrationMetadata.Id
{
get { return "201510010029257_InitialMigration"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
namespace Queries.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class InitialMigration : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Authors",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Courses",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 255),
Description = c.String(nullable: false, maxLength: 2000),
Level = c.Int(nullable: false),
FullPrice = c.Single(nullable: false),
AuthorId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Authors", t => t.AuthorId)
.Index(t => t.AuthorId);
CreateTable(
"dbo.Covers",
c => new
{
Id = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Courses", t => t.Id)
.Index(t => t.Id);
CreateTable(
"dbo.Tags",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.CourseTags",
c => new
{
CourseId = c.Int(nullable: false),
TagId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.CourseId, t.TagId })
.ForeignKey("dbo.Courses", t => t.CourseId, cascadeDelete: true)
.ForeignKey("dbo.Tags", t => t.TagId, cascadeDelete: true)
.Index(t => t.CourseId)
.Index(t => t.TagId);
}
public override void Down()
{
DropForeignKey("dbo.CourseTags", "TagId", "dbo.Tags");
DropForeignKey("dbo.CourseTags", "CourseId", "dbo.Courses");
DropForeignKey("dbo.Covers", "Id", "dbo.Courses");
DropForeignKey("dbo.Courses", "AuthorId", "dbo.Authors");
DropIndex("dbo.CourseTags", new[] { "TagId" });
DropIndex("dbo.CourseTags", new[] { "CourseId" });
DropIndex("dbo.Covers", new[] { "Id" });
DropIndex("dbo.Courses", new[] { "AuthorId" });
DropTable("dbo.CourseTags");
DropTable("dbo.Tags");
DropTable("dbo.Covers");
DropTable("dbo.Courses");
DropTable("dbo.Authors");
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Target" xml:space="preserve">
<value>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</value>
</data>
<data name="DefaultSchema" xml:space="preserve">
<value>dbo</value>
</data>
</root>
\ No newline at end of file
using Queries.Core.Domain;
using Queries.Persistence;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Queries.Migrations
{
using System.Data.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<PlutoContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(PlutoContext context)
{
#region Add Tags
var tags = new Dictionary<string, Tag>
{
{"c#", new Tag {Id = 1, Name = "c#"}},
{"angularjs", new Tag {Id = 2, Name = "angularjs"}},
{"javascript", new Tag {Id = 3, Name = "javascript"}},
{"nodejs", new Tag {Id = 4, Name = "nodejs"}},
{"oop", new Tag {Id = 5, Name = "oop"}},
{"linq", new Tag {Id = 6, Name = "linq"}},
};
foreach (var tag in tags.Values)
context.Tags.AddOrUpdate(t => t.Id, tag);
#endregion
#region Add Authors
var authors = new List<Author>
{
new Author
{
Id = 1,
Name = "Mosh Hamedani"
},
new Author
{
Id = 2,
Name = "Anthony Alicea"
},
new Author
{
Id = 3,
Name = "Eric Wise"
},
new Author
{
Id = 4,
Name = "Tom Owsiak"
},
new Author
{
Id = 5,
Name = "John Smith"
}
};
foreach (var author in authors)
context.Authors.AddOrUpdate(a => a.Id, author);
#endregion
#region Add Courses
var courses = new List<Course>
{
new Course
{
Id = 1,
Name = "C# Basics",
Author = authors[0],
FullPrice = 49,
Description = "Description for C# Basics",
Level = 1,
Tags = new Collection<Tag>()
{
tags["c#"]
}
},
new Course
{
Id = 2,
Name = "C# Intermediate",
Author = authors[0],
FullPrice = 49,
Description = "Description for C# Intermediate",
Level = 2,
Tags = new Collection<Tag>()
{
tags["c#"],
tags["oop"]
}
},
new Course
{
Id = 3,
Name = "C# Advanced",
Author = authors[0],
FullPrice = 69,
Description = "Description for C# Advanced",
Level = 3,
Tags = new Collection<Tag>()
{
tags["c#"]
}
},
new Course
{
Id = 4,
Name = "Javascript: Understanding the Weird Parts",
Author = authors[1],
FullPrice = 149,
Description = "Description for Javascript",
Level = 2,
Tags = new Collection<Tag>()
{
tags["javascript"]
}
},
new Course
{
Id = 5,
Name = "Learn and Understand AngularJS",
Author = authors[1],
FullPrice = 99,
Description = "Description for AngularJS",
Level = 2,
Tags = new Collection<Tag>()
{
tags["angularjs"]
}
},
new Course
{
Id = 6,
Name = "Learn and Understand NodeJS",
Author = authors[1],
FullPrice = 149,
Description = "Description for NodeJS",
Level = 2,
Tags = new Collection<Tag>()
{
tags["nodejs"]
}
},
new Course
{
Id = 7,
Name = "Programming for Complete Beginners",
Author = authors[2],
FullPrice = 45,
Description = "Description for Programming for Beginners",
Level = 1,
Tags = new Collection<Tag>()
{
tags["c#"]
}
},
new Course
{
Id = 8,
Name = "A 16 Hour C# Course with Visual Studio 2013",
Author = authors[3],
FullPrice = 150,
Description = "Description 16 Hour Course",
Level = 1,
Tags = new Collection<Tag>()
{
tags["c#"]
}
},
new Course
{
Id = 9,
Name = "Learn JavaScript Through Visual Studio 2013",
Author = authors[3],
FullPrice = 20,
Description = "Description Learn Javascript",
Level = 1,
Tags = new Collection<Tag>()
{
tags["javascript"]
}
}
};
foreach (var course in courses)
context.Courses.AddOrUpdate(c => c.Id, course);
#endregion
}
}
}
using Queries.Core.Domain;
using System.Data.Entity.ModelConfiguration;
namespace Queries.Persistence.EntityConfigurations
{
public class CourseConfiguration : EntityTypeConfiguration<Course>
{
public CourseConfiguration()
{
Property(c => c.Description)
.IsRequired()
.HasMaxLength(2000);
Property(c => c.Name)
.IsRequired()
.HasMaxLength(255);
HasRequired(c => c.Author)
.WithMany(a => a.Courses)
.HasForeignKey(c => c.AuthorId)
.WillCascadeOnDelete(false);
HasRequired(c => c.Cover)
.WithRequiredPrincipal(c => c.Course);
HasMany(c => c.Tags)
.WithMany(t => t.Courses)
.Map(m =>
{
m.ToTable("CourseTags");
m.MapLeftKey("CourseId");
m.MapRightKey("TagId");
});
}
}
}
\ No newline at end of file
using Queries.Core.Domain;
using Queries.Persistence.EntityConfigurations;
using System.Data.Entity;
namespace Queries.Persistence
{
public class PlutoContext : DbContext
{
public PlutoContext()
: base("name=PlutoContext")
{
this.Configuration.LazyLoadingEnabled = false;
}
public virtual DbSet<Author> Authors { get; set; }
public virtual DbSet<Course> Courses { get; set; }
public virtual DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CourseConfiguration());
}
}
}
using Queries.Core.Domain;
using Queries.Core.Repositories;
using System.Data.Entity;
using System.Linq;
namespace Queries.Persistence.Repositories
{
public class AuthorRepository : Repository<Author>, IAuthorRepository
{
public AuthorRepository(PlutoContext context) : base(context)
{
}
public Author GetAuthorWithCourses(int id)
{
return PlutoContext.Authors.Include(a => a.Courses).SingleOrDefault(a => a.Id == id);
}
public PlutoContext PlutoContext
{
get { return Context as PlutoContext; }
}
}
}
\ No newline at end of file
using Queries.Core.Domain;
using Queries.Core.Repositories;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace Queries.Persistence.Repositories
{
public class CourseRepository : Repository<Course>, ICourseRepository
{
public CourseRepository(PlutoContext context)
: base(context)
{
}
public IEnumerable<Course> GetTopSellingCourses(int count)
{
return PlutoContext.Courses.OrderByDescending(c => c.FullPrice).Take(count).ToList();
}
public IEnumerable<Course> GetCoursesWithAuthors(int pageIndex, int pageSize = 10)
{
return PlutoContext.Courses
.Include(c => c.Author)
.OrderBy(c => c.Name)
.Skip((pageIndex - 1) * pageSize)
.Take(pageSize)
.ToList();
}
public PlutoContext PlutoContext
{
get { return Context as PlutoContext; }
}
}
}
\ No newline at end of file
using Queries.Core.Repositories;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
namespace Queries.Persistence.Repositories
{
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected readonly DbContext Context;
public Repository(DbContext context)
{
Context = context;
}
public TEntity Get(int id)
{
// Here we are working with a DbContext, not PlutoContext. So we don't have DbSets
// such as Courses or Authors, and we need to use the generic Set() method to access them.
return Context.Set<TEntity>().Find(id);
}
public IEnumerable<TEntity> GetAll()
{
// Note that here I've repeated Context.Set<TEntity>() in every method and this is causing
// too much noise. I could get a reference to the DbSet returned from this method in the
// constructor and store it in a private field like _entities. This way, the implementation
// of our methods would be cleaner:
//
// _entities.ToList();
// _entities.Where();
// _entities.SingleOrDefault();
//
// I didn't change it because I wanted the code to look like the videos. But feel free to change
// this on your own.
return Context.Set<TEntity>().ToList();
}
public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
{
return Context.Set<TEntity>().Where(predicate);
}
public TEntity SingleOrDefault(Expression<Func<TEntity, bool>> predicate)
{
return Context.Set<TEntity>().SingleOrDefault(predicate);
}
public void Add(TEntity entity)
{
Context.Set<TEntity>().Add(entity);
}
public void AddRange(IEnumerable<TEntity> entities)
{
Context.Set<TEntity>().AddRange(entities);
}
public void Remove(TEntity entity)
{
Context.Set<TEntity>().Remove(entity);
}
public void RemoveRange(IEnumerable<TEntity> entities)
{
Context.Set<TEntity>().RemoveRange(entities);
}
}
}
\ No newline at end of file
using Queries.Core;
using Queries.Core.Repositories;
using Queries.Persistence.Repositories;
namespace Queries.Persistence
{
public class UnitOfWork : IUnitOfWork
{
private readonly PlutoContext _context;
public UnitOfWork(PlutoContext context)
{
_context = context;
Courses = new CourseRepository(_context);
Authors = new AuthorRepository(_context);
}
public ICourseRepository Courses { get; private set; }
public IAuthorRepository Authors { get; private set; }
public int Complete()
{
return _context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
}
\ No newline at end of file
using Queries.Persistence;
using System;
namespace Queries
{
class Program
{
static void Main(string[] args)
{
using (var unitOfWork = new UnitOfWork(new PlutoContext()))
{
// Example1
var course = unitOfWork.Courses.Get(2);
// Example2
var courses = unitOfWork.Courses.GetCoursesWithAuthors(1, 4);
Console.WriteLine(course.Name);
// Example3
/*var author = unitOfWork.Authors.GetAuthorWithCourses(1);
unitOfWork.Courses.RemoveRange(author.Courses);
unitOfWork.Authors.Remove(author);
unitOfWork.Complete();*/
}
}
}
}
\ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Queries")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Queries")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0485f195-b128-4fd3-84d9-01e25288bf61")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\EntityFramework.6.4.4\build\EntityFramework.props" Condition="Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{D1776DED-C59A-4F8A-8C31-96EAE15BDF5A}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Queries</RootNamespace>
<AssemblyName>Queries</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.dll</HintPath>
</Reference>
<Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.SqlServer.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Core\Domain\Author.cs" />
<Compile Include="Persistence\Repositories\AuthorRepository.cs" />
<Compile Include="Core\Domain\Course.cs" />
<Compile Include="Persistence\Repositories\CourseRepository.cs" />
<Compile Include="Core\Domain\Cover.cs" />
<Compile Include="Persistence\EntityConfigurations\CourseConfiguration.cs" />
<Compile Include="Core\Repositories\IAuthorRepository.cs" />
<Compile Include="Core\Repositories\ICourseRepository.cs" />
<Compile Include="Core\Repositories\IRepository.cs" />
<Compile Include="Core\IUnitOfWork.cs" />
<Compile Include="Migrations\201510010029257_InitialMigration.cs" />
<Compile Include="Migrations\201510010029257_InitialMigration.Designer.cs">
<DependentUpon>201510010029257_InitialMigration.cs</DependentUpon>
</Compile>
<Compile Include="Migrations\Configuration.cs" />
<Compile Include="Persistence\PlutoContext.cs" />
<Compile Include="Program.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Persistence\Repositories\Repository.cs" />
<Compile Include="Core\Domain\Tag.cs" />
<Compile Include="Persistence\UnitOfWork.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Migrations\201510010029257_InitialMigration.resx">
<DependentUpon>201510010029257_InitialMigration.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\EntityFramework.6.4.4\build\EntityFramework.props'))" />
<Error Condition="!Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\EntityFramework.6.4.4\build\EntityFramework.targets'))" />
</Target>
<Import Project="..\packages\EntityFramework.6.4.4\build\EntityFramework.targets" Condition="Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.4.4" targetFramework="net48" />
</packages>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment