엔터티 프레임 워크 및 SQL Server보기
내가 말할 자유가없는 몇 가지 이유로, 우리는 다음과 같이 Sql Server 2005 데이터베이스에 대한 견해를 정의하고 있습니다.
CREATE VIEW [dbo].[MeterProvingStatisticsPoint]
AS
SELECT
CAST(0 AS BIGINT) AS 'RowNumber',
CAST(0 AS BIGINT) AS 'ProverTicketId',
CAST(0 AS INT) AS 'ReportNumber',
GETDATE() AS 'CompletedDateTime',
CAST(1.1 AS float) AS 'MeterFactor',
CAST(1.1 AS float) AS 'Density',
CAST(1.1 AS float) AS 'FlowRate',
CAST(1.1 AS float) AS 'Average',
CAST(1.1 AS float) AS 'StandardDeviation',
CAST(1.1 AS float) AS 'MeanPlus2XStandardDeviation',
CAST(1.1 AS float) AS 'MeanMinus2XStandardDeviation'
WHERE 0 = 1
아이디어는 Entity Framework 가이 쿼리를 기반으로 엔티티를 작성하지만 다음과 같은 오류가 발생하여 엔티티를 생성한다는 것입니다.
경고 6002 : 테이블 / 뷰 'Keystone_Local.dbo.MeterProvingStatisticsPoint'에 기본 키가 정의되어 있지 않습니다. 키가 유추되었으며 정의가 읽기 전용 테이블 / 뷰로 작성되었습니다.
그리고 CompletedDateTime 필드가이 엔티티 기본 키가되도록 결정합니다.
우리는 EdmGen을 사용하여 모델을 생성하고 있습니다. 엔터티 프레임 워크에이 뷰의 필드를 기본 키로 포함시키지 않는 방법이 있습니까?
우리는 같은 문제가 있었고 이것이 해결책입니다.
엔티티 프레임 워크가 열을 기본 키로 사용하도록하려면 ISNULL을 사용하십시오.
엔티티 프레임 워크가 열을 기본 키로 사용하지 않도록하려면 NULLIF를 사용하십시오.
이것을 적용하는 쉬운 방법은 뷰의 select 문을 다른 select로 감싸는 것입니다.
예:
SELECT
ISNULL(MyPrimaryID,-999) MyPrimaryID,
NULLIF(AnotherProperty,'') AnotherProperty
FROM ( ... ) AS temp
디자이너를 사용하여이 문제를 해결할 수있었습니다.
- 모델 브라우저를 엽니 다.
- 다이어그램에서보기를 찾으십시오.
- 기본 키를 마우스 오른쪽 버튼으로 클릭하고 "엔터티 키"가 선택되어 있는지 확인하십시오.
- 기본이 아닌 모든 키를 여러 개 선택하십시오. Ctrl 또는 Shift 키를 사용하십시오.
- 속성 창에서 (필요한 경우 F4 키를 누름) "엔터티 키"드롭 다운을 False로 변경하십시오.
- 변경 사항을 저장하다.
- Visual Studio를 닫았다가 다시여십시오. EF 6과 함께 Visual Studio 2013을 사용하고 있으며 경고를 없애기 위해이 작업을 수행해야했습니다.
ISNULL, NULLIF 또는 COALESCE 해결 방법을 사용하기 위해보기를 변경할 필요가 없었습니다. 데이터베이스에서 모델을 업데이트하면 경고가 다시 나타나지만 VS를 닫았다가 다시 열면 사라집니다. 디자이너에서 변경 한 내용은 유지되며 새로 고침의 영향을받지 않습니다.
@Tillito에 동의하지만 대부분의 경우 SQL 최적화 프로그램을 손상시키고 올바른 인덱스를 사용하지 않습니다.
누군가에게는 분명 할 수 있지만 Tillito 솔루션을 사용하여 성능 문제를 해결하는 데 몇 시간을 소비했습니다. 테이블이 있다고 가정 해 봅시다.
Create table OrderDetail
(
Id int primary key,
CustomerId int references Customer(Id),
Amount decimal default(0)
);
Create index ix_customer on OrderDetail(CustomerId);
당신의 관점은 다음과 같습니다
Create view CustomerView
As
Select
IsNull(CustomerId, -1) as CustomerId, -- forcing EF to use it as key
Sum(Amount) as Amount
From OrderDetail
Group by CustomerId
SQL Optimizer는 인덱스 ix_customer를 사용하지 않고 기본 인덱스에서 테이블 스캔을 수행하지만 다음과 같은 경우에 수행합니다.
Group by CustomerId
너는 사용한다
Group by IsNull(CustomerId, -1)
MS SQL (적어도 2008 년)은 올바른 인덱스를 계획에 포함시킵니다.
만약
This method works well for me. I use ISNULL() for the primary key field, and COALESCE() if the field should not be the primary key, but should also have a non-nullable value. This example yields ID field with a non-nullable primary key. The other fields are not keys, and have (None) as their Nullable attribute.
SELECT
ISNULL(P.ID, - 1) AS ID,
COALESCE (P.PurchaseAgent, U.[User Nickname]) AS PurchaseAgent,
COALESCE (P.PurchaseAuthority, 0) AS PurchaseAuthority,
COALESCE (P.AgencyCode, '') AS AgencyCode,
COALESCE (P.UserID, U.ID) AS UserID,
COALESCE (P.AssignPOs, 'false') AS AssignPOs,
COALESCE (P.AuthString, '') AS AuthString,
COALESCE (P.AssignVendors, 'false') AS AssignVendors
FROM Users AS U
INNER JOIN Users AS AU ON U.Login = AU.UserName
LEFT OUTER JOIN PurchaseAgents AS P ON U.ID = P.UserID
if you really don't have a primary key, you can spoof one by using ROW_NUMBER to generate a pseudo-key that is ignored by your code. For example:
SELECT
ROW_NUMBER() OVER(ORDER BY A,B) AS Id,
A, B
FROM SOMETABLE
The current Entity Framework EDM generator will create a composite key from all non-nullable fields in your view. In order to gain control over this, you will need to modify the view and underlying table columns setting the columns to nullable when you do not want them to be part of the primary key. The opposite is also true, as I encountered, the EDM generated key was causing data-duplication issues, so I had to define a nullable column as non-nullable to force the composite key in the EDM to include that column.
Looks like it is a known problem with EdmGen: http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/12aaac4d-2be8-44f3-9448-d7c659585945/
To get a view I had to only show one primary key column I created a second view that pointed to the first and used NULLIF to make the types nullable. This worked for me to make the EF think there was just a single primary key in the view.
Not sure if this will help you though since I don't believe the EF will accept an entity with NO primary key.
If you do not want to mess with what should be the primary key, I recommend:
- Incorporate
ROW_NUMBERinto your selection - Set it as primary key
- Set all other columns/members as non-primary in the model
Due to the above mentioned problems, I prefer table value functions.
If you have this:
CREATE VIEW [dbo].[MyView] AS SELECT A, B FROM dbo.Something
create this:
CREATE FUNCTION MyFunction() RETURNS TABLE AS RETURN (SELECT * FROM [dbo].[MyView])
Then you simply import the function rather than the view.
참고URL : https://stackoverflow.com/questions/1013333/entity-framework-and-sql-server-view
'Programming' 카테고리의 다른 글
| AngularJs : 페이지 새로 고침 (0) | 2020.06.30 |
|---|---|
| Homebrew Cask를 통해 설치된 모든 통을 업그레이드하십시오. (0) | 2020.06.30 |
| 외래 키 제약 조건을 무시하고 mysql을 강제로 삭제하십시오. (0) | 2020.06.30 |
| -viewWillAppear :와 -viewDidAppear :의 차이점은 무엇입니까? (0) | 2020.06.30 |
| 스크립트에서 sys.argv [1] 의미 (0) | 2020.06.30 |